using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using InABox.Clients;
using InABox.Core;
using InABox.WPF;

namespace InABox.DynamicGrid
{
    /// <summary>
    ///     Interaction logic for ImageEditorControl.xaml
    /// </summary>
    public partial class ImageEditorControl : UserControl, IDocumentEditor
    {
        private IEntityDocument? _document;

        private byte[] documentdata;


        public ImageEditorControl()
        {
            InitializeComponent();
            Editor.ToolbarSettings.IsToolbarVisiblity = false;
        }

        public IEntityDocument? Document
        {
            get => _document;
            set
            {
                UnloadImage();
                _document = value;
                LoadImage();
                //PDFDocumentLoaded?.Invoke(this, value);
            }
        }


        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),
                new Columns<Document>(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 LoadImage()
        {
            if (_document is null)
                return;

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

            using (new WaitCursor())
            {
                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);
                }

                var img = new BitmapImage();
                img.LoadImage(documentdata);
                Editor.ImageSource = img;
            }
        }

        private void UnloadImage()
        {
            if (Editor.ImageSource != null)
                Editor.ImageSource = null;
        }
    }
}