using System;
using System.Text;

using Microsoft.EntityFrameworkCore;
using GZTW.Pecklist.Models;

namespace GZTW.Pecklist.Util
{
    //Key generator controller
    public static class Schema
    {
        private static PecklistContext ctx;

        /////////////////////////////////////////////////////////////////
        /////////// CHANGE THIS ON NEW SCHEMA UPDATE ////////////////////
        public const int DESIRED_SCHEMA_LEVEL = 2;
        /////////////////////////////////////////////////////////////////


        static int startingSchema = -1;
        static int currentSchema = -1;

        //check and update schema
        public static void CheckAndUpdate(PecklistContext context)
        {
            ctx = context;
            bool AppSchemaExists = false;
            //  var ld=context.ListData;

            //update schema here?           
            using (var command = ctx.Database.GetDbConnection().CreateCommand())
            {
                //first of all, do we have a schema table yet (v0?)
                command.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='appschema';";
                ctx.Database.OpenConnection();
                using (var result = command.ExecuteReader())
                {
                    if (result.HasRows)
                    {
                        AppSchemaExists = true;
                    }
                    ctx.Database.CloseConnection();
                }
            }
            //Create schema table (v1)
            if (!AppSchemaExists)
            {
                //nope, no schema table, add it now and set to v1
                using (var cmCreateappschema = ctx.Database.GetDbConnection().CreateCommand())
                {
                    context.Database.OpenConnection();
                    //first of all, do we have a schema table yet (v0?)
                    cmCreateappschema.CommandText = "CREATE TABLE appschema (id INTEGER PRIMARY KEY, schema INTEGER NOT NULL);";
                    cmCreateappschema.ExecuteNonQuery();

                    cmCreateappschema.CommandText = "insert into appschema (schema) values (1);";
                    cmCreateappschema.ExecuteNonQuery();

                    context.Database.CloseConnection();
                    startingSchema = 1;
                    currentSchema = 1;
                }
            }
            else
            {
                //get current schema level
                using (var cm = ctx.Database.GetDbConnection().CreateCommand())
                {
                    cm.CommandText = "SELECT schema FROM appschema WHERE id=1;";
                    ctx.Database.OpenConnection();
                    using (var result = cm.ExecuteReader())
                    {
                        if (result.HasRows)
                        {
                            result.Read();
                            currentSchema = startingSchema = result.GetInt32(0);
                            ctx.Database.CloseConnection();
                        }
                        else
                        {
                            ctx.Database.CloseConnection();
                            throw new System.Exception("Pecklist->RfSchema->CheckAndUpdate: Error reading schema version");
                        }
                    }
                }
            }

            //Bail early no update?
            if (currentSchema == DESIRED_SCHEMA_LEVEL)
                return;



            //************* SCHEMA UPDATES ******************
            //////////////////////////////////////////////////
            //schema 2 import data from Foodoo
            if (currentSchema < 2)
            {
                //empty out the listdata table
                exec("delete from listdata");

                //Trigger import of foodoo data 
                Util.FoodooImporter.Import(ctx);

                //open and read in the GZListServerBackup.bak file into a json object
                //turn it into pecklist format
                //write it into the db
                //$profit$

                currentSchema = 2;              
                setSchemaLevel(currentSchema);
            }

            //*************************************************************************************


        }//eofunction



        private static void setSchemaLevel(int nCurrentSchema)
        {
            exec("UPDATE appschema SET schema=" + nCurrentSchema.ToString());
        }

        //execute command query
        private static void exec(string q)
        {
            using (var cmCreateappschema = ctx.Database.GetDbConnection().CreateCommand())
            {
                ctx.Database.OpenConnection();
                cmCreateappschema.CommandText = q;
                cmCreateappschema.ExecuteNonQuery();
                ctx.Database.CloseConnection();
            }
        }

        //eoclass
    }
    //eons
}