using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Notification;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using pavesys_iRAP.Business;
using pavesys_iRAP.DTO;
using pavesys_iRAP.Helper;
using Serilog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Avalonia.Layout;
using System.Diagnostics;
using System.Threading.Tasks;
using System.IO;
using DynamicData;



namespace pavesys_iRAP.ViewModels
{
    public partial class ProjectsPageViewModel : ViewModelBase
    {
        //Notification Handlers
        [ObservableProperty]
        private INotificationMessageManager manager = new NotificationMessageManager();
        public List<INotificationMessage> Messages { get; } = new List<INotificationMessage>();
        [ObservableProperty]
        private bool isNotLoading = true;
        [ObservableProperty]
        private bool isViaEnabled = false;
        // ------------
        public Project? SelecProject { get; set; }
        [ObservableProperty]
        private ObservableCollection<Project> projects;



        public RelayCommand deleteProject { get; }
        public RelayCommand<string> exportProj { get; }
        public RelayCommand Json { get; set; }
        public ProjectsPageViewModel(IEnumerable<Project> projects , bool hasViaSeguraAccess)
        {
            deleteProject = new(DeleteProject);
            exportProj = new(ExportProj);


            //int closed = StatusProject.CLOSED.GetHashCode();
            //var projectQry = from prj in ctx.Projects
            //                 where prj.Status != closed
            //                 select prj;

            Projects = new ObservableCollection<Project>(projects);
            IsViaEnabled = hasViaSeguraAccess;
        }
        public async void ImportZip(string zipFilePath)
        {
            try
            {
                ExportImportHandler exporter = new();
                IsNotLoading = false;
                DialogHelper.ShowLoadingQueryNotification(Localizer.Localizer.Instance["Importing"], $"{Localizer.Localizer.Instance["ImportingProject"]}", Manager);
                var importedProj = await exporter.Import(zipFilePath);
                if (importedProj != null)
                {
                    Projects.Add(importedProj);
                }
                else
                {
                    await DialogHelper.ShowOkDialog("Warning", "CheckLogs");
                }
                await DialogHelper.DismissLoadingNotification(Manager);
                IsNotLoading = true;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error Importing Zip ProjectsPage");
                await DialogHelper.DismissLoadingNotification(Manager);
                IsNotLoading = true;
                await DialogHelper.ShowOkDialog("Warning", "CheckLogs");

            }
        }
        public async void ExportProj(string ExportType)
        {
            if (SelecProject is null)
            {
                await DialogHelper.ShowOkDialog("NoProjectSelected", "SelectProject");
                return;
            }
            Manager = new NotificationMessageManager();
            try
            {
                IsNotLoading = false;
                DialogHelper.ShowLoadingQueryNotification(Localizer.Localizer.Instance["Exporting"], $"{Localizer.Localizer.Instance["ExportingProject"]} - {SelecProject.Road}", Manager);
                if (ExportType == "sheet")
                {
                    await XlsxHandler.ExecuteOutput((int)SelecProject.ProjectId, 0);

                }
                else if (ExportType == "zip")
                {
                    try
                    {
                        ExportImportHandler exportImportHandler = new ExportImportHandler();
                        await exportImportHandler.ExecuteExport((int)SelecProject.ProjectId);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Error ExporingZip");
                    }
                }
                else if (ExportType == "csv")
                {
                    await XlsxHandler.ExecuteOutputCSV((int)SelecProject.ProjectId, 0);
                }



                await DialogHelper.DismissLoadingNotification(Manager);
                IsNotLoading = true;
            }
            catch (Exception e)
            {
                await DialogHelper.DismissLoadingNotification(Manager);
                IsNotLoading = true;
                await DialogHelper.ShowOkDialog("Error", "ExportError");
                Log.Error(e, "Error Exporting Project");
            }
        }
        public async void DeleteProject()
        {
            if (SelecProject != null)
            {
                if (!await DialogHelper.ShowYesNoDialog("Warning", "AskDelete", MsBox.Avalonia.Enums.Icon.Info))
                    return;

                try
                {
                    IsNotLoading = false;
                    DialogHelper.ShowLoadingQueryNotification(Localizer.Localizer.Instance["Deleting"], $"{Localizer.Localizer.Instance["DeletingProject"]} - {SelecProject.Road}", Manager);
                    CrudHelper.dbCtx.RemoveRange(CrudHelper.FindCodingsByProject((int)SelecProject.ProjectId, false));
                    await CrudHelper.dbCtx.SaveChangesAsync();

                    CrudHelper.RefreshContext();
                    //CrudHelper.dbCtx.RemoveRange(await CrudHelper.FindCodingImagesByProjectId((int)SelecProject.ProjectId));
                    CrudHelper.dbCtx.Remove(SelecProject);
                    await CrudHelper.dbCtx.SaveChangesAsync();
                    //Delete photo folder
                    var projpath = SelecProject.ProjectPath;
                    //Para garantir ao deletar projetos que não foram criados corretamente não ira deletar a pasta do vídeo
                    if (projpath.Contains(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)))
                    {
                        if (Directory.Exists(projpath))
                            Directory.Delete(projpath, true);
                    }
                    Projects.Remove(SelecProject);
                    await DialogHelper.DismissLoadingNotification(Manager);
                    IsNotLoading = true;
                }
                catch (Exception e)
                {
                    await DialogHelper.DismissLoadingNotification(Manager);
                    await DialogHelper.ShowOkDialog("Error", "ErrorDeleting");
                    IsNotLoading = true;
                    Log.Error(e, "Error Deleting Project");
                }
            }
            else
                await DialogHelper.ShowOkDialog("NoProjectSelected", "SelectProject");
        }
    }
}
