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

namespace BookmarkManager
{
    public class JSONSupportedFile : SupportedFileBase
    {


        public JSONSupportedFile()
        {
            supportedExtensions = new List<string>() { ".json" };
        }


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

        public override bool IsEncrypted(string filename) => false;

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

            string sourceCode = null;

            try
            {
                sourceCode = System.IO.File.ReadAllText(filename);
            }
            catch (Exception exc)
            {
                return Result.Create(false, "Could not read file (" + exc.Message + ")");
            }

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

            for (int i = 0; i < rs.Count; i++)
            {
                if (treeview.InvokeRequired)
                {
                    treeview.Invoke(new MethodInvoker(() => {
                        treeview.AddItem(rs[i]);
                    }));
                }
                else
                {
                    treeview.AddItem(rs[i]);
                }
            }

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

            try
            {
                System.IO.File.WriteAllText(filename, JsonConvert.SerializeObject(rs));
            }
            catch (Exception exc)
            {
                return Result.Create(false, "Could not write file (" + exc.Message + ")");
            }

            return Result.Create(true);
        }

    }
}
