using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace ZionVault.Synonym
{
    public class Document : ZionVault.Util.Xml, IDisposable
    {

        private string description;
        private string path;
        private List<Area> areas;

        public string Description { get => description; set => description = value; }
        public string Path { get => path; set => path = value; }
        public List<Area> Areas { get => areas; set => areas = value; }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }

        public Document(string path)
        {
            this.path = path;
            this.Load(this.path, @"document");

            XmlNode root = this.SelectSingleNode(@"document");

            this.description = root.Attributes[@"description"].Value;
            this.path = root.Attributes[@"path"].Value;

            this.areas = new List<Area>();
            foreach(XmlElement element in this.GetElementsByTagName(@"area"))
            {
                this.areas.Add(new Area(element));
            }
        }

        public Document(string description, string path, List<Area> areas)
        {
            Description = description;
            Path = path;
            Areas = areas;
        }

        public void Save()
        {
            if(this.path != null)
            {
                this.Save(this.path);
            }
        }
        public void Save(string path)
        {
            System.IO.FileInfo info = new System.IO.FileInfo(path);
            this.Save(info.Directory.FullName, info.Name, true);
        }

        public void Save(string Path, string FileName, bool Encrypt)
        {
            ZionVault.Util.Xml xml = new ZionVault.Util.Xml();

            xml.AppendChild(xml.CreateXmlDeclaration("1.0", @"UTF-8", @"yes"));

            XmlElement root = xml.CreateElement(@"document");

            root.SetAttribute(@"description", this.description);
            root.SetAttribute(@"path", this.path);
            
            if(this.areas.Count() > 0)
            {
                this.areas.ForEach(area =>
                {
                    root.AppendChild(area.Export(xml));
                });
            }

            xml.AppendChild(root);
            xml.Save(string.Format(@"{0}\{1}", Path, FileName), @"document", Encrypt);
        }
    }
}
