using bzit.bomg.Models;
using Newtonsoft.Json;
using RyzStudio.IO;
using RyzStudio.Windows.Forms;
using System.Collections.Generic;
using System.Windows.Forms;

namespace BookmarkManager
{
    public class JSNXSupportedFile : SupportedFileBase
    {


        public JSNXSupportedFile()
        {
            supportedExtensions = new List<string>() { ".jsnx" };
        }


        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.json");
            if (string.IsNullOrWhiteSpace(sourceCode))
            {
                return Result.Create(false, "Could not read file, unexpected format");
            }

            List<BookmarkItem> rs = JsonConvert.DeserializeObject<List<BookmarkItem>>(sourceCode);
            if (rs == null)
            {
                return Result.Create(false, "Could not read file, incorrect format");
            }

            //// load bookmark items
            //ThreadControl.SetValue(progressBar1, 0, rs.Count);

            for (int i = 0; i < rs.Count; i++)
            {
                //    ThreadControl.SetValue(progressBar1, (i + 1));

                if (treeview.InvokeRequired)
                {
                    treeview.Invoke(new MethodInvoker(() => {
                        treeview.AddItem(rs[i]);
                    }));
                }
                else
                {
                    treeview.AddItem(rs[i]);
                }
            }

            //treeview.SetNoChanges();

            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");
            }

            bool rv = SharpZipLib.CreateSingle(filename, password, "bookmarks.json", JsonConvert.SerializeObject(rs));

            return Result.Create(rv);
        }

    }
}
