using Agent86.Models;
using Agent86.OpenIDConnect;
using Dapper;
using MySqlConnector;

namespace Agent86.Persistence
{
    public class DbOps
    {
        #region General

        private Boolean isDebug { get; set; }

        public DbOps()
        {
            isDebug = MyConfiguration.Get()["DEBUG"] == "Y";
        }

        private string GetConnectionString()
        {
            string myConnectionString = MyConfiguration.Get()["MARIA_DB_CONNECT"];
            if (myConnectionString == null)
            {
                if (isDebug) Console.WriteLine("Connectionstring: Default");
                return ("server=localhost;user id=agent86;password=12tf56so;persistsecurityinfo=True;database=Agent86");
            }
            else
            {
                if (isDebug) Console.WriteLine("Connectionstring: " + myConnectionString);
                return myConnectionString;
            }
        }

        private void CreateIfNotExist(MySqlConnection myDbConnection)
        {
            // Create tables if not there
            myDbConnection.Open();
            myDbConnection.Execute("CREATE TABLE IF NOT EXISTS `Scene` ( `role` VARCHAR(50) NOT NULL DEFAULT 'error' COLLATE 'latin1_bin', `quest` VARCHAR(256) NOT NULL DEFAULT 'error' COLLATE 'latin1_bin', `me` VARCHAR(50) NULL DEFAULT 'error' COLLATE 'latin1_bin', `customer` VARCHAR(50) NULL DEFAULT 'error' COLLATE 'latin1_bin', `instruction` VARCHAR(16834) NULL DEFAULT 'error' COLLATE 'latin1_bin', PRIMARY KEY (`role`) USING BTREE ) COLLATE='latin1_bin' ENGINE=InnoDB ;");
        }

        private string GetGuid()
        {
            return System.Guid.NewGuid().ToString();
        }

        #endregion General

        #region Operations

        public List<Scene> GetScenes()
        {
            using (var myDbConnection = new MySqlConnection(GetConnectionString()))
            {
                CreateIfNotExist(myDbConnection);
                var scenes = myDbConnection.Query<Scene>("SELECT * FROM Scene").ToList();
                return scenes;
            }
        }

        #endregion Operations

    }
}
