using System;
using System.Collections.Generic;
using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;

namespace BlubbFish.Utils.IoT.Connector.User {
  public class Telegram : AUserBackend {
    private TelegramBotClient bot;
    private ChatId chat;

    public override event TelegramMessage MessageIncomming;
    public override event TelegramMessage MessageSending;

    public Telegram(Dictionary<String, String> settings) : base(settings) {
      this.bot = new TelegramBotClient(settings["telegram-key"]);
      this.bot.OnMessage += this.Bot_OnMessage;
      this.Connect();
    }

    private void Bot_OnMessage(Object sender, MessageEventArgs e) {
      this.MessageIncomming?.Invoke(this, new UserMessageEventArgs(e.Message.Text, e.Message.Chat.Id, e.Message.Date));
    }

    private void Connect() {
      this.bot.StartReceiving();
      this.chat = new ChatId(this.settings["chatid"]);
    }

    public async override void Send(String message) {
      try {
        Message x = await this.bot.SendTextMessageAsync(this.chat, message, ParseMode.Default, false, false, 0, new ReplyKeyboardRemove());
        this.MessageSending?.Invoke(this, new UserMessageEventArgs(x.Text, x.Chat.Id, x.Date));
      } catch(ApiRequestException e) {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(e.Message+" "+e.ErrorCode+" "+e.Parameters);
        Console.ForegroundColor = ConsoleColor.White;
      }
      
    }

    public override void Dispose() {
      this.bot.StopReceiving();
      this.bot = null;
    }

    public async override void Send(String message, String[] buttons) {
      try {
        KeyboardButton[][] button = new KeyboardButton[(Int32)Math.Ceiling(((Double)buttons.Length)/2)][];
        for(Int32 i = 0; i < buttons.Length; i++) {
          Int32 j = (Int32)Math.Floor(((Double)i) / 2);
          if (i % 2 == 0) {
            button[j] = new KeyboardButton[(j == button.Length - 1) ? ((buttons.Length % 2 == 0) ? 2 : buttons.Length % 2) : 2];
          }
          button[j][i % 2] = new KeyboardButton(buttons[i]);
        }
        Message x = await this.bot.SendTextMessageAsync(this.chat, message, ParseMode.Default, false, false, 0, new ReplyKeyboardMarkup(button,true,true));
        this.MessageSending?.Invoke(this, new UserMessageEventArgs(x.Text, x.Chat.Id, x.Date));
      } catch (ApiRequestException e) {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(e.Message + " " + e.ErrorCode + " " + e.Parameters);
        Console.ForegroundColor = ConsoleColor.White;
      }
    }
  }
}