using System.Threading.Tasks;
using Elwig.Helpers;
using Elwig.Windows;
using System.Diagnostics;
using Balbarak.WeasyPrint;
using System;
using System.IO;

namespace Elwig.Documents {
    public static class Pdf {

        private static readonly string PdfToPrinter = App.ExePath + "PDFtoPrinter.exe";
        private static readonly FilesManager WeasyPrintManager = new();
        private static string? WeasyPrintPython = null;
        private static string? WeasyPrintDir => WeasyPrintManager.FolderPath;
        public static bool IsReady => WeasyPrintPython != null && WeasyPrintDir != null;

        public static async Task Init(Action evtHandler) {
            if (!WeasyPrintManager.IsFilesExsited()) {
                await WeasyPrintManager.InitFilesAsync();
            }
            WeasyPrintPython = Path.Combine(WeasyPrintManager.FolderPath, "python.exe");
            evtHandler();
        }

        public static async Task Convert(string htmlPath, string pdfPath) {
            var p = new Process() { StartInfo = new() {
                FileName = WeasyPrintPython,
                CreateNoWindow = true,
                WorkingDirectory = WeasyPrintDir,
                RedirectStandardError = true,
            } };
            p.StartInfo.EnvironmentVariables["PATH"] = "Scripts;gtk3;" + Environment.GetEnvironmentVariable("PATH");
            p.StartInfo.ArgumentList.Add("scripts/weasyprint.exe");
            p.StartInfo.ArgumentList.Add("-e");
            p.StartInfo.ArgumentList.Add("utf8");
            p.StartInfo.ArgumentList.Add(htmlPath);
            p.StartInfo.ArgumentList.Add(pdfPath);
            p.Start();
            await p.WaitForExitAsync();
            var stderr = await p.StandardError.ReadToEndAsync();
            if (p.ExitCode != 0) throw new Exception(stderr);
        }

        public static void Show(TempFile file, string title) {
            App.MainDispatcher.BeginInvoke(() => {
                var w = new DocumentViewerWindow(title, file);
                w.Show();
            });
        }

        public static void Show(string path, string title) {
            App.MainDispatcher.BeginInvoke(() => {
                var w = new DocumentViewerWindow(title, path);
                w.Show();
            });
        }

        public static async Task Print(string path, int copies = 1) {
            var p = new Process() { StartInfo = new() { FileName = PdfToPrinter } };
            p.StartInfo.ArgumentList.Add(path);
            p.StartInfo.ArgumentList.Add("/s");
            p.StartInfo.ArgumentList.Add($"copies={copies}");
            p.Start();
            await p.WaitForExitAsync();
        }
    }
}