using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using InABox.Clients;
using InABox.Core;
using InABox.DynamicGrid;
using InABox.WPF;
using Syncfusion.UI.Xaml.Spreadsheet.Helpers;
using Syncfusion.Windows.Controls.RichTextBoxAdv;

namespace InABox.DynamicGrid
{
    public partial class RTFEditorControl : UserControl, IDocumentEditor
    {
        
        private IEntityDocument? _document;

        public RTFEditorControl()
        {
            InitializeComponent();
        }
        public IEntityDocument? Document
        {
            get => _document;
            set
            {
                Unload();
                _document = value;
                Load();
            }
        }


        private bool DownloadNeeded(Guid id)
        {
            var cachefile = Path.Combine(CoreUtils.GetPath(), string.Format("{0}.ffd", id.ToString()));

            if (!File.Exists(cachefile))
                return true;

            var indexfile = Path.Combine(CoreUtils.GetPath(), "pdfindex.json");
            if (!File.Exists(indexfile))
                return true;

            var json = File.ReadAllText(indexfile);
            var index = Serialization.Deserialize<Dictionary<Guid, string>>(json);
            if (!index.ContainsKey(id))
                return true;
            var entry = new Client<Document>().Query(
                new Filter<Document>(x => x.ID).IsEqualTo(id),
                Columns.None<Document>().Add(x => x.CRC)
            ).Rows.FirstOrDefault();
            if (entry == null)
                return true;
            if (!entry.Get<Document, string>(x => x.CRC).Equals(index[id]))
            {
                MessageBox.Show("This document has been revised, and will now refresh.\n\nPlease check the drawing for any applicable changes.");
                return true;
            }

            return false;
        }

        private void Load()
        {
            if (_document == null)
                return;

            var cachefile = Path.Combine(CoreUtils.GetPath(), string.Format("{0}.ffd", _document.DocumentLink.ID.ToString()));

            using (new WaitCursor())
            {
                byte[] documentdata;
                if (DownloadNeeded(_document.DocumentLink.ID))
                {
                    var dbdoc = new Client<Document>().Load(new Filter<Document>(x => x.ID).IsEqualTo(_document.DocumentLink.ID)).FirstOrDefault();
                    if (dbdoc == null)
                    {
                        MessageBox.Show("Unable to Load File!");
                        return;
                    }

                    var indexfile = Path.Combine(CoreUtils.GetPath(), "pdfindex.json");
                    var index = new Dictionary<Guid, string>();
                    if (File.Exists(indexfile))
                    {
                        var json = File.ReadAllText(indexfile);
                        index = Serialization.Deserialize<Dictionary<Guid, string>>(json);
                    }

                    index[_document.DocumentLink.ID] = dbdoc.CRC;
                    File.WriteAllText(indexfile, Serialization.Serialize(index));

                    documentdata = dbdoc.Data;
                    File.WriteAllBytes(cachefile, documentdata);
                }
                else
                {
                    documentdata = File.ReadAllBytes(cachefile);
                }
                
                using (var ms = new MemoryStream(documentdata))
                {
                    var format = Path.GetExtension(_document.DocumentLink.FileName).ToLower() switch
                    {
                        "docx" => FormatType.Docx,
                        "doc" => FormatType.Doc,
                        "html" => FormatType.Html,
                        "htm" => FormatType.Html,
                        "rtf" => FormatType.Rtf,
                        _ => FormatType.Txt
                    };
                    Editor.Load(ms, format);
                }

            }
        }

        private void Unload()
        {
            if (_document != null)
            {
                Editor.Document = null;
                _document = null;
            }
        }

        private void Editor_OnWorkbookLoaded(object sender, WorkbookLoadedEventArgs args)
        {
            Editor.IsReadOnly = true;
        }
    }
}