using bzit.bomg.Models;
using RyzStudio.IO;
using RyzStudio.Windows.Forms;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace BookmarkManager
{
    public class RYZSupportedFile : SupportedFileBase
    {


        public RYZSupportedFile()
        {
            supportedExtensions = new List<string>() { ".ryz" };
        }


        public override bool IsEncryptionSupported { get; set; } = true;

        public override bool IsEncrypted(string filename) => SharpZipLib.IsZipEncrypted(filename);

        public override Result Load(BookmarkTreeView treeview, string filename, string password)
        {
            treeview.Clear();

            if (!SharpZipLib.TestArchive(filename, password))
            {
                return Result.Create(false, "Could not read file, is password correct?");
            }

            string sourceCode = SharpZipLib.ReadSingle(filename, password, "bookmarks.xml");
            if (string.IsNullOrWhiteSpace(sourceCode))
            {
                return Result.Create(false, "Could not read file, unexpected format");
            }

            // load xml
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(sourceCode);

            // parse
            XmlNode xnl = xmlDocument.SelectSingleNode("bomg/b/g");
            if (xnl == null)
            {
                return Result.Create(false, "Could not load file, unexpected format");
            }

            string rootName = (xnl.Attributes["name"] == null) ? "Bookmarks" : (string.IsNullOrWhiteSpace(xnl.Attributes["name"].InnerText) ? "Bookmarks" : xnl.Attributes["name"].InnerText.Trim());

            foreach (XmlNode xn in xnl.ChildNodes)
            {
                BookmarkItem item = new BookmarkItem();

                foreach (XmlNode xn2 in xn.ChildNodes)
                {
                    switch (xn2.LocalName)
                    {
                        case "name":
                            item.SiteName = xn2.InnerText?.Trim();
                            break;
                        case "address":
                            item.SiteAddress = xn2.InnerText?.Trim();
                            break;
                        case "description":
                            item.SiteDescription = xn2.InnerText?.Trim();
                            break;
                        case "notes":
                            item.Notes = xn2.InnerText?.Trim();
                            break;
                        //case "created":
                        //    bi.Created = xn2.InnerText?.Trim();
                        //    break;
                        default:
                            break;
                    }
                }

                // fix fullpath and name
                if (item.SiteName.Contains("|"))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("\\");
                    sb.Append(System.Web.HttpUtility.UrlEncode(rootName));
                    sb.Append("\\");

                    string[] pathParts = item.SiteName.Split('|');
                    for (int i = 0; i < (pathParts.Length - 1); i++)
                    {
                        sb.Append(pathParts[i]);
                        //sb.Append(System.Web.HttpUtility.UrlDecode(pathParts[i]));
                        sb.Append("\\");
                    }

                    item.SiteName = System.Web.HttpUtility.UrlDecode(pathParts[(pathParts.Length - 1)] ?? string.Empty);
                    item.TreeviewPath = sb.ToString();
                }
                else
                {
                    item.SiteName = System.Web.HttpUtility.UrlDecode(item.SiteName);
                    item.TreeviewPath = string.Format("\\{0}\\", System.Web.HttpUtility.UrlEncode(rootName));
                }

                if (treeview.InvokeRequired)
                {
                    treeview.Invoke(new MethodInvoker(() =>
                    {
                        treeview.AddItem(item);
                    }));
                }
                else
                {
                    treeview.AddItem(item);
                }
            }

            return Result.Create(true);
        }

        public override Result Save(BookmarkTreeView treeview, string filename, string password)
        {
            List<BookmarkItem> rs = treeview.GetBookmarkList();
            if (rs.Count <= 0)
            {
                return Result.Create(false, "No bookmarks to save");
            }

            return Result.Create(false, "Saving in this format is no longer supported");

            //MemoryStream ms = new MemoryStream();
            //XmlTextWriter writer = new XmlTextWriter(ms, Encoding.UTF8);

            //writer.Formatting = Formatting.Indented;
            //writer.WriteStartDocument();
            //writer.WriteStartElement("bomg");
            //writer.WriteStartElement("b");
            //writer.WriteStartElement("g");
            //writer.WriteAttributeString("name", treeview.Nodes[0].Text);

            //foreach (BookmarkItem item in rs)
            //{
            //    writer.WriteStartElement("m");
            //    writer.WriteElementString("name", item.TreeviewPath);
            //    writer.WriteElementString("address", item.SiteAddress);
            //    writer.WriteElementString("description", item.SiteDescription);
            //    writer.WriteElementString("created", "200101010000");
            //    writer.WriteEndElement();
            //}

            //writer.WriteEndElement();
            //writer.WriteEndElement();
            //writer.WriteEndElement();
            //writer.WriteEndDocument();
            //writer.Flush();

            //ms.Position = 0;
            //StreamReader sr = new StreamReader(ms);

            //string sourceCode = sr.ReadToEnd();

            //sr.Close();
            //sr.Dispose();

            //writer.Close();
            //writer.Dispose();

            //bool rv = SharpZipLib.CreateSingle(filename, password, "bookmarks.xml", sourceCode);

            //return Result.Create(rv);
        }

    }
}
