using CommunityToolkit.Maui.Alerts;
using CommunityToolkit.Maui.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Threading;
using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.MAUI.DataLayer;
using WorkFlowCheck.MAUI.Helper;
using WorkFlowCheck.MAUI.Services;
using WorkFlowCheck.MAUI.Services.Interfaces;

namespace WorkFlowCheck.MAUI
{
    public partial class App : Application
    {
        private readonly AppDbContext _dbContext;
        private readonly IUserService _userService;
        private readonly ISyncService _syncService;
        private CancellationTokenSource _cancellationTokenSource;

        public App(IServiceProvider serviceProvider)
        {
            InitializeComponent();

            _dbContext = serviceProvider.GetRequiredService<AppDbContext>();
            _userService = serviceProvider.GetRequiredService<IUserService>();
            _syncService = serviceProvider.GetRequiredService<ISyncService>();

            _dbContext.Database.EnsureDeleted(); // Adatbázis törlése
            _dbContext.Database.EnsureCreated(); // Új adatbázis létrehozása

            //StartBackgroundTask();
            MainPage = new AppShell();
            //MainPage = new NavigationPage(new MainPage(serviceProvider.GetRequiredService<IUserService>()));

        }
        protected async override void OnResume()
        {
            //StartBackgroundTask();
            base.OnResume();
            var isLogged = await SecureStorage.Default.GetAsync("WFCUser");
            if (isLogged == null)
            {

            }
        }
        protected override void OnSleep()
        {
            _cancellationTokenSource?.Cancel();
            SecureStorage.Default.Remove("WFCUser");
            base.OnSleep();
        }
        protected async override void OnStart()
        {
            base.OnStart();
            SecureStorage.Default.Remove("WFCUser");
            await Shell.Current.GoToAsync("//LoginPage");
        }


        private void StartBackgroundTask()
        {
            _cancellationTokenSource = new CancellationTokenSource();
            Task.Run(() => BackgroundTask(_cancellationTokenSource.Token));
        }
        private async Task BackgroundTask(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var userDTO = _userService.GetCurrentUser();

                    if (userDTO != null && userDTO.Id > 0 && SystemHelper.Syncronised)
                    {
                        if (userDTO.RoleDTO?.Count > 0)
                        {
                            foreach (var roleDTO in userDTO.RoleDTO)
                            {
                                if (roleDTO.CanEnableBlocked)
                                {
                                    var deviceMessageDTOList = await _syncService.DeviceMessageReadUnreaded(_userService.DeviceId.ToUpper());
                                    if (deviceMessageDTOList != null && deviceMessageDTOList.Count > 0)
                                    {
                                        await ShowSnackbar(deviceMessageDTOList[0].Message, async () => await GoToCheckListPage());
                                        break;
                                    }
                                    deviceMessageDTOList = await _syncService.DeviceMessageReadUnreadedRole(roleDTO.Id);
                                    if (deviceMessageDTOList != null && deviceMessageDTOList.Count > 0)
                                    {
                                        await ShowSnackbar(deviceMessageDTOList[0].Message, async () => await GoToCheckListPage());
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {

                }
                await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
            }
        }
        private async Task GoToCheckListPage() 
        {
            await Shell.Current.GoToAsync("//CheckListPage");
        }
        private async Task ShowSnackbar(string message, Func<Task> action)
        {
#if ANDROID
            try
            {
                var context = Android.App.Application.Context;
                var player = Android.Media.MediaPlayer.Create(context, Resource.Raw.siren_alert);
                player.Start();

                // Ha lejátszás után el akarod engedni az erőforrást:
                player.Completion += (s, e) =>
                {
                    player.Release();
                    player.Dispose();
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine("Hanglejátszás hiba: " + ex.Message);
            }
#endif

            var visualOptions = new SnackbarOptions
            {
                ActionButtonTextColor = Colors.Yellow,
                CornerRadius = new CornerRadius(5),
                Font = Microsoft.Maui.Font.SystemFontOfSize(16),
                BackgroundColor = Microsoft.Maui.Graphics.Color.Parse("Red"),
                TextColor = Colors.Yellow
            };

            var snackbar = Snackbar.Make(message,
                duration: TimeSpan.FromSeconds(10),
                action: async () => await action(),
                actionButtonText: "OK",
                visualOptions: visualOptions
            );

            await snackbar.Show();
        }

        private async Task<ApiResponseDTO<UserDTO>> CheckSecurity()
        {
            var isLogged = await SecureStorage.Default.GetAsync("WFCUser");
            if (isLogged == null)
            {
                return new ApiResponseDTO<UserDTO>()
                {
                    IsSuccess = false
                };
            }
            return new ApiResponseDTO<UserDTO>()
            {
                IsSuccess = true
            };
        }
    }
}
