using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Schema;

namespace FooEditor
{
    public class FileModel : IXmlSerializable
    {
        public StorageFile File
        {
            get;
            private set;
        }

        public FileModel(StorageFile file)
        {
            this.File = file;
        }

        public string Path
        {
            get
            {
                return this.File.Path;
            }
        }

        public string Name
        {
            get
            {
                return this.File.Name;
            }
        }

        public static async Task<FileModel> GetFileModelAsync(string file_name,bool overwrite = false)
        {
            return new FileModel(await ApplicationData.Current.LocalFolder.GetFileAsync(file_name));
        }

        public static async Task<FileModel> CreateFileModel(string file_name,bool overwrite = false)
        {
            CreationCollisionOption coll_opt = overwrite ? CreationCollisionOption.ReplaceExisting : CreationCollisionOption.FailIfExists;
            return new FileModel(await ApplicationData.Current.LocalFolder.CreateFileAsync(file_name,coll_opt));
        }

        public static async Task<FileModel> GetFileModelAsync(Uri uri)
        {
            return new FileModel(await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri));
        }

        public async Task<Stream> GetReadStreamAsync()
        {
            return await this.File.OpenStreamForReadAsync();
        }

        public async Task<Stream> GetWriteStreamAsync()
        {
            return await this.File.OpenStreamForWriteAsync();
        }

        public async Task DeleteAsync()
        {
            await this.File.DeleteAsync();
        }

        public XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            reader.ReadStartElement("FileModel");
            reader.ReadStartElement("FilePath");
            string path = reader.ReadContentAsString();
            this.File = StorageFile.GetFileFromPathAsync(path).GetResults();
            reader.ReadEndElement();
            reader.ReadEndElement();
        }

        public void WriteXml(XmlWriter writer)
        {
            writer.WriteStartElement("FileModel");
            writer.WriteStartElement("FilePath");
            writer.WriteString(this.File.Path);
            writer.WriteEndElement();
            writer.WriteEndElement();
        }
    }
}
