using System;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using GZTW.Pecklist.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;

namespace GZTW.Pecklist.Util
{
    public static class FoodooImporter
    {
        public static void Import(PecklistContext ct)
        {
            //open and read in the GZListServerBackup.bak file into a json object
            //https://www.newtonsoft.com/json/help/html/LINQtoJSON.htm
            string sfoo = GetBackupFile();
            JArray jin = JArray.Parse(sfoo);
            JArray jout = new JArray();

            foreach (JObject i in jin)
            {
                JObject o = new JObject();
                o["name"] = (string)i["name"];
                o["id"] = Util.ShortId.Generate();
                o["name_v"] = (long)i["name_v"];
                o["v"] = (long)i["v"];
                JArray oitems = new JArray();
                foreach (JObject l in i["items"])
                {
                    JObject oitem = new JObject();
                    oitem["id"] = Util.ShortId.Generate();
                    oitem["completed"] = (bool)l["completed"];
                    oitem["text"] = (string)l["text"];
                    oitem["v"] = (long)l["v"];
                    var highlight = (bool?)l["highlight"];
                    if (highlight == null)
                    {
                        oitem["priority"] = 1;//default priority
                    }
                    else
                    {
                        oitem["priority"] = 3;//highest priority
                    }
                    oitems.Add(oitem);
                }
                o["items"] = oitems;
                jout.Add(o);
            }

            //write it into the db
            ListData ldat = new ListData();

            //this is the most compact way to write the json out as text
            ldat.TheList = JsonConvert.SerializeObject(jout);           
            
            ct.ListData.Add(ldat);
            ct.SaveChanges();
        }



        private static string GetBackupFile()
        {
            try
            {   // Open the text file using a stream reader.
                using (StreamReader sr = new StreamReader("./db/GZListServerBackup.bak"))
                {
                    // Read the stream to a string, and write the string to the console.
                    String line = sr.ReadToEnd();
                    return line;
                }
            }
            catch
            {
                return null;
            }

        }

        //--------
    }
}