using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using System.Text.Json;
using Telegram.Bot.Types.ReplyMarkups;

namespace LC_Api
{
    public class Program
    {
        public static string token = "7055214362:AAFL1aroXt1S00pACH6jMs7OiNQtmK8pI_Y";
        public static TelegramBotClient botClient = null;
        public static void Main(string[] args)
        {
            botClient = new TelegramBotClient(token);
            using CancellationTokenSource cts = new();


            var builder = WebApplication.CreateBuilder(args);
            using var db = new Db();
            builder.Services.AddAuthorization();

            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            var app = builder.Build();

            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseAuthorization();

            app.MapGet("/", () => "status:ok");

            app.MapGet("/error", () =>
            {
                var re = db.Errors.ToList();
                if (re.Count > 0)
                {
                    return re;
                }
                return null;
            });
            app.MapGet("/error/{countDay}", (int countDay) =>
            {
                DateTime d = DateTime.Now.AddDays(-countDay);
                List<Error> re;
                switch (countDay)
                {
                    case 0:
                        re = db.Errors.Where(e => e.DataError == DateTime.Now).ToList();
                        break;
                    case 3:
                        re = db.Errors.Where(e => e.DataError <= DateTime.Now && e.DataError > d).ToList();
                        break;
                    case 7:
                        re = db.Errors.Where(e => e.DataError <= DateTime.Now && e.DataError > d).ToList();
                        break;
                    default:
                        re = new List<Error>();
                        break;
                }
                //var data = content.Content.ToString();
                //var er =  JsonSerializer.Deserialize<Error>(content);
                //db.Error.Add(content);
                //db.SaveChanges();
                return re;
            });

            app.MapPost("/error", async (Error content) =>
            {
                var txt = string.Empty;
                content.DataError = DateTime.Now;

                InlineKeyboardMarkup inlineKeyboard = new(new[]
                    {
                        new []
                        {
                            InlineKeyboardButton.WithCallbackData(text: "Перезагрузить", callbackData: $"reboot|{content.Ip}")
                        }
                    });

                if (content.Status == "off")
                {
                    txt = "<b>‼ НЕИСПРАВНОСТЬ ‼</b>\n" +
                    $"----------------------------------------------\n" +
                    $"<b>Объект:</b> {content.Map}\n" +
                    $"<b>Устройство:</b> {content.TypeDev}\n" +
                    $"<b>Имя:</b> {content.Name}\n" +
                    $"<b>Адрес:</b> {content.Ip}\n" +
                    $"<b>Состояние:</b> 🔴 - не доступна\n" +
                    $"----------------------------------------------";
                    var msgId = botClient.SendTextMessageAsync(chatId: 6882856105, parseMode: ParseMode.Html, replyMarkup: inlineKeyboard, text: txt).Result.MessageId;
                    content.MsgId = msgId;
                    db.Errors.Add(content);
                    db.SaveChanges();
                }
                else if (content.Status == "error")
                {
                    var re = db.Errors.SingleOrDefault(e => e.Ip == content.Ip && e.Status == "off");
                    if (re != null)
                    {
                        re.Status = "error";
                        re.DataError = content.DataError;
                        txt = "<b>⚠ ВНИМАНИЕ ⚠</b>\n" +
                        $"----------------------------------------------\n" +
                        $"<b>Объект:</b> {content.Map}\n" +
                        $"<b>Устройство:</b> {content.TypeDev}\n" +
                        $"<b>Имя:</b> {content.Name}\n" +
                        $"<b>Адрес:</b> {content.Ip}\n" +
                        $"<b>Состояние:</b> 🟡 - ошибка\n" +
                        $"----------------------------------------------";
                        //var mi = Convert.ToInt32(re.MsgId);
                        //await botClient.DeleteMessageAsync(6882856105, mi);
                        var msgId = botClient.EditMessageTextAsync(6882856105, re.MsgId, txt, parseMode: ParseMode.Html);
                        re.MsgId = msgId.Id;
                        db.SaveChanges();
                    }
                    else 
                    {
                        txt = "<b>⚠ ВНИМАНИЕ ⚠</b>\n" +
                        $"----------------------------------------------\n" +
                        $"<b>Объект:</b> {content.Map}\n" +
                        $"<b>Устройство:</b> {content.TypeDev}\n" +
                        $"<b>Имя:</b> {content.Name}\n" +
                        $"<b>Адрес:</b> {content.Ip}\n" +
                        $"<b>Состояние:</b> 🟡 - ошибка\n" +
                        $"----------------------------------------------";
                        var msgId = botClient.SendTextMessageAsync(chatId: 6882856105, parseMode: ParseMode.Html, text: txt).Result.MessageId;
                        content.MsgId = msgId;
                        db.Errors.Add(content);
                        db.SaveChanges();
                    }
                }
                else
                {
                    var re = db.Errors.FirstOrDefault(e => e.Ip == content.Ip && (e.Status == "off" || e.Status == "error") && e.Name == content.Name);
                    if (re != null)
                    {
                        re.Status = "on";
                        re.DataError = content.DataError;
                        txt = "<b>✅ ИСПРАВНО ✅</b>\n" +
                        $"----------------------------------------------\n" +
                        $"<b>Объект:</b> {content.Map}\n" +
                        $"<b>Устройство:</b> {content.TypeDev}\n" +
                        $"<b>Имя:</b> {content.Name}\n" +
                        $"<b>Адрес:</b> {content.Ip}\n" +
                        $"<b>Состояние:</b> 🟢 - исправно\n" +
                        $"----------------------------------------------";
                        var msgId = botClient.DeleteMessageAsync(6882856105, re.MsgId);// EditMessageTextAsync(6882856105, re.MsgId, txt, parseMode: ParseMode.Html);
                        re.MsgId = msgId.Id;
                    }
                    db.SaveChanges();
                }
                return;
            });

            app.Run();
        }

        private static async Task HandlePollingErrorAsync(ITelegramBotClient client, Exception exception, CancellationToken token)
        {
            throw new NotImplementedException();
        }

        private static async Task HandleUpdateAsync(ITelegramBotClient client, Update update, CancellationToken token)
        {
            return;
        }
    }
}
