using CefSharpWrap;
using System;
using System.IO;
using System.Windows.Forms;

namespace MarkdownRenderer
{
    public partial class PrintToPdfForm : Form
    {
        private readonly CefSharpWrapBrowser _sourceBrowser;
        private readonly CefSharpWrapBrowser _previewBrowser;
        private readonly CefSharpWrapPdfExportSetting _printSettings;

        private string _tempPdfFile;

        public PrintToPdfForm(CefSharpWrapBrowser sourceBrowser)
        {
            _sourceBrowser = sourceBrowser;

            InitializeComponent();

            _previewBrowser = CefSharpWrapFactory.CreateLocalFileAccessInstance("about:blank");
            _previewBrowser.FillToControl(MainSplitContainer.Panel2);

            //TODO: Read print setting from config store
            _printSettings = new CefSharpWrapPdfExportSetting();
            _printSettings.BackgroundsEnabled = true;

            PrintSettingPropertyGrid.SelectedObject = _printSettings;

            UpdatePreview();
        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
            UpdatePreview();
        }

        private void PrintSettingPropertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            UpdatePreview();
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            var sfd = new SaveFileDialog
            {
                Title = "Save as PDF",
                Filter = "PDF files (*.pdf)|*.pdf"
            };

            if (DialogResult.OK != sfd.ShowDialog()) return;

            try
            {
                if (File.Exists(sfd.FileName)) File.Delete(sfd.FileName);
                File.Move(_tempPdfFile, sfd.FileName);
                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString(), "Save as PDF fail", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void UpdatePreview()
        {
            if (null != _tempPdfFile) File.Delete(_tempPdfFile);

            _tempPdfFile = Path.GetTempFileName();
            File.Move(_tempPdfFile, _tempPdfFile += ".pdf");
            _sourceBrowser.ExportAsPdf(_tempPdfFile, _printSettings);
            _previewBrowser.LoadUrl($"file:///{_tempPdfFile}");
        }

        private void PrintToPdfForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (null != _tempPdfFile) File.Delete(_tempPdfFile);
            if (DialogResult.OK == DialogResult)
            {
                //TODO: Save print setting into config store
            }
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
    }
}