using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FooEditEngine;
using System.Xml.Serialization;
using EncodeDetect;

namespace FooEditor
{
    class DocumentTypeEventArg
    {
        /// <summary>
        /// 適用すべきハイライター。nullならクリアする必要がある
        /// </summary>
        public IHilighter hilighter;
        /// <summary>
        /// 適用すべき折り畳み。nullならクリアする必要がある
        /// </summary>
        public IFoldingStrategy folding;
        /// <summary>
        /// 新しく設定されたファイルタイプ
        /// </summary>
        public FileType newFileType;

        public DocumentTypeEventArg(FileType newFileType)
        {
            this.newFileType = newFileType;
        }
    }

    class DocumentModel
    {
        public FileModel currentFile
        {
            get;
            private set;
        }

        public string Title
        {
            get;
            set;
        }

        public bool IsProgressNow
        {
            get;
            set;
        }

        public bool IsDirty
        {
            get;
            set;
        }

        public FileType DocumentType
        {
            get;
            private set;
        }

        public Encoding Encode
        {
            get;
            set;
        }

        public LineFeedType LineFeed
        {
            get;
            set;
        }

        public DocumentModel()
        {
            this.Encode = Encoding.Unicode;
            this.LineFeed = LineFeedType.CRLF;
            this.DocumentTypeChanged += (s, e)=>{ };
        }

        public event EventHandler<DocumentTypeEventArg> DocumentTypeChanged;

        public Func<FileModel, Encoding, Task> LoadFileImpl;

        public Func<FileModel, Encoding, LineFeedType, Task> SaveFileImpl;

        public async Task SetDocumentType(FileType type)
        {
            this.DocumentType = type;

            if (type == null || string.IsNullOrEmpty(type.DocumentType))
            {
                this.DocumentTypeChanged(this, new DocumentTypeEventArg(type));
                return;
            }

            FileModel file;
            try
            {
                var uri = new System.Uri("ms-appx:///Keywords/" + type.DocumentType);
                file = await FileModel.GetFileModelAsync(uri);
            }
            catch (FileNotFoundException)
            {
                this.DocumentTypeChanged(this, new DocumentTypeEventArg(type));
                return;
            }

            var tuple = EditorHelper.GetFoldingAndHilight(file.Path);
            var arg = new DocumentTypeEventArg(type);
            arg.hilighter = tuple.Item2;
            arg.folding = tuple.Item1;
            this.DocumentTypeChanged(this, arg);
        }

        private FileType GetFileType(string file)
        {
            ObservableCollection<FileType> collection = AppSettings.Current.FileTypeCollection;
            foreach (FileType type in collection)
                foreach (string ext in type.ExtensionCollection)
                    if (Path.GetExtension(file) == ext)
                        return type;
            return null;
        }

        public async Task LoadFile(FileModel file, Encoding enc = null)
        {
            this.IsProgressNow = true;
            try
            {
                if (enc == null)
                {
                    using (Stream stream = await file.GetReadStreamAsync())
                    {
                        enc = await DectingEncode.GetEncodingAsync(stream);
                    }
                    if (enc == null)
                        enc = Encoding.Unicode;
                }
                this.Encode = enc;

                using (Stream stream = await file.GetReadStreamAsync())
                {
                    this.LineFeed = await LineFeedHelper.GetLineFeedAsync(stream, enc);
                }

                await this.SetDocumentType(GetFileType(file.Name));

                await this.LoadFileImpl(file,enc);

                this.currentFile = file;
                this.IsDirty = false;
#if TEST_PROGRESS
                await Task.Delay(10000);
#endif
            }
            finally
            {
                this.IsProgressNow = false;
            }
        }

        public async Task ReloadFile(Encoding enc)
        {
            if (this.currentFile == null)
                return;
            this.Encode = enc;
            await this.LoadFileImpl(this.currentFile, enc);
            this.IsDirty = false;
        }

        public async Task SaveFile(FileModel file)
        {
            await this.SaveFileImpl(file, this.Encode, this.LineFeed);
            this.IsDirty = false;
        }

        public const string prefixFileName = "save_";

        public async Task RestoreCurrentFile(string title,FileModel currentFile,string documentType)
        {
            FileModel file = await FileModel.GetFileModelAsync(prefixFileName + this.Title);
            await this.LoadFile(file);
            await file.DeleteAsync();

            this.currentFile = currentFile;

            if (documentType != string.Empty)
            {
                foreach (FileType type in AppSettings.Current.FileTypeCollection)
                    if (type.DocumentType == documentType)
                    {
                        await this.SetDocumentType(type);
                        break;
                    }
            }
        }

        public async Task SaveCurrentFile()
        {
            FileModel file = await FileModel.CreateFileModel(prefixFileName + this.Title, true);
            await this.SaveFile(file);
        }
    }
}
