using Dapper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using WK_KLI_LAPS_Service.Models.Configuration;
using WK_KLI_LAPS_Service.Models.Master;

namespace WK_KLI_LAPS_Service.App_Data
{
    public class SmartChartRepository
    {
        CommonRepository oCommonRepository = new CommonRepository();



        /// Check the given smart chart exists or not       
        public bool CheckExists(string name, int id)
        {
            bool result = false;
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spsmartchartconfigselect";
                param.Add("smartchartname_p", name);
                param.Add("smartchartconfigid_p", id);
                param.Add("mode_p", "checkexistence");
                var smartChartConfiglist = dbConnection.Query<smartChartModel>(query, param, commandType: CommandType.StoredProcedure);
                if (smartChartConfiglist.Count() > 0)
                    result = true;
                return result;
            }
        }

        private string RemoveSplchar(Match match)
        {
            string val = match.Value;
            try
            {
                string pre = match.Groups[1].Value;
                string post = match.Groups[2].Value;
                post = Regex.Replace(post, @"[<>_()*$+~&#^@;:.\-=]", "", RegexOptions.Singleline);
                return pre + post;
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return val;
            }
        }

        //to insert newly added smart chart information
        public int add(object data, string name, string htmldata)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                bool smartChartConfiglistExists = CheckExists(name, 0);
                int result = 0;
                string result1 = "";
                if (smartChartConfiglistExists == false)
                {

                    Regex reg = new Regex(@"(""formcontrolname"":)(""[^""]*[<>_()*$+~&#^@;:.\-=][^""]*"")");
                    string htmldatmodified1 = Regex.Replace(htmldata, @"(""formcontrolname"":)(""[^""]*[<>_()*$+~&#^@;:.\-=][^""]*"")", RemoveSplchar, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    JArray htmldatmodified = JArray.Parse(htmldatmodified1) as JArray;
                    //}
                    var JAformated = new JArray();
                    foreach (JObject item in htmldatmodified)
                    {
                        var jObject = new JObject();
                        var Propertytype = item.Property("type");
                        if (Propertytype != null)
                        {
                            jObject.Add(item.Property("type"));
                        }
                        var Propertyname = item.Property("formcontrolname");
                        if (Propertyname != null)
                        {
                            jObject.Add(item.Property("formcontrolname"));
                        }

                        JAformated.Add(jObject);
                    }

                    dynamic f = JsonConvert.DeserializeObject(JAformated.ToString());
                    dynamic json = JsonConvert.SerializeObject(f);
                    var param = new DynamicParameters();
                    param.Add("smartchartname", name.ToLower());
                    param.Add("inputjsonstr", json);
                    param.Add("mode_p", "create");
                    result1 = dbConnection.Query<string>("spsmartchartdynamictable", param, commandType: CommandType.StoredProcedure).First();

                    if (result1 == "created")
                    {
                        string input = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                        string query = @"public.spsmartchartconfigmaster";
                        param = new DynamicParameters();
                        param.Add("inputjsonstr", input);
                        param.Add("mode_p", "insert");
                        result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();
                        //code to add user activity log 
                        if (result != 0)
                        {
                            useractivitylogModel userlogmodel;
                            userlogmodel = new useractivitylogModel();
                            userlogmodel.useraction = "Add smart chart  Config information";
                            userlogmodel.description = "Added smart chart Config information.Added id is" + result;
                            oCommonRepository.useractivityAdd(userlogmodel);

                        }
                    }
                    else
                    {
                        return 0;
                    }


                }

                return result;
            }
        }

        //code to edit specific data
        public int Edit(object data, string name, int id, string htmldata)
        {

            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                bool _formTemplateExists = CheckExists(name, id);
                int result = 0;
                string result1 = "";
                if (_formTemplateExists == false)
                {

                    Regex reg = new Regex(@"(""formcontrolname"":)(""[^""]*[<>_()*$+~&#^@;:.\-=][^""]*"")");
                    string htmldatmodified1 = Regex.Replace(htmldata, @"(""formcontrolname"":)(""[^""]*[<>_()*$+~&#^@;:.\-=][^""]*"")", RemoveSplchar, RegexOptions.IgnoreCase | RegexOptions.Singleline);

                    JArray htmldatmodified = JArray.Parse(htmldatmodified1) as JArray;
                    //}
                    var JAformated = new JArray();
                    foreach (JObject item in htmldatmodified)
                    {
                        var jObject = new JObject();
                        var Propertytype = item.Property("type");
                        if (Propertytype != null)
                        {
                            jObject.Add(item.Property("type"));
                        }
                        var Propertyname = item.Property("formcontrolname");
                        if (Propertyname != null)
                        {
                            jObject.Add(item.Property("formcontrolname"));
                        }

                        JAformated.Add(jObject);
                    }

                    dynamic f = JsonConvert.DeserializeObject(JAformated.ToString());
                    dynamic json = JsonConvert.SerializeObject(f);

                    var param = new DynamicParameters();
                    param.Add("smartchartname", name.ToLower());
                    param.Add("inputjsonstr", json);
                    param.Add("mode_p", "update");
                    result1 = dbConnection.Query<string>("spsmartchartdynamictable", param, commandType: CommandType.StoredProcedure).First();

                    string input = JsonConvert.SerializeObject(data);
                    string query = @"public.spsmartchartconfigmaster";
                    param = new DynamicParameters();
                    param.Add("inputjsonstr", input);
                    param.Add("mode_p", "update");
                    result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();

                }
                //code to add user activity log
                if (result != 0)
                {

                    useractivitylogModel userlogmodel;
                    userlogmodel = new useractivitylogModel();
                    userlogmodel.useraction = "Edit smart chart  Config information";
                    userlogmodel.description = "Edit smart chart Config information.Added id is" + result;
                    oCommonRepository.useractivityAdd(userlogmodel);

                }
                return result;
            }
        }

        public object getByID(int id)
        {
            // bool result = false;
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spsmartchartconfigselect";
                param.Add("smartchartconfigid_p", id);
                param.Add("mode_p", "getbyid");
                return dbConnection.Query<object>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        //get all master details
        public IEnumerable<object> GetAllGivenMasterDetails(string tableId)
        {
            using (System.Data.IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spallmastertableselect";
                param.Add("tableid_p", tableId);
                return dbConnection.Query<object>(query, param, commandType: CommandType.StoredProcedure);
            }

        }
        // insert newly added form information
        public int addSmartChartData(object data, string formconfigid, string tablename)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                int result = 0;
                string query = @"public.spsmartchartformrender";
                dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(data.ToString());
                string input = Newtonsoft.Json.JsonConvert.SerializeObject(json);
                var param = new DynamicParameters();
                param.Add("inputjsonstr", input);
                param.Add("mode_p", "insert");
                result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();
                //code to add user activity log 
                if (result != 0)
                {
                    useractivitylogModel userlogmodel;
                    userlogmodel = new useractivitylogModel();
                    userlogmodel.useraction = "Add Smart Chart Data  Form Render information";
                    userlogmodel.description = "Added Smart Chart Data Form Render information.Added id is" + result + " in the table " + tablename;
                    oCommonRepository.useractivityAdd(userlogmodel);
                }

                return result;
            }
        }

        public string getAllSmartChartAnswercount(object data)
        {
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    DynamicParameters param = new DynamicParameters();
                    const string query = @"public.spgetsmartchartconfigrowcount";
                    var jsonstr = JsonConvert.SerializeObject(data);
                    param.Add("inputjsonstr", jsonstr);
                    param.Add("mode_p", "getrowcount");
                    dbConnection.Open();
                    return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                throw new Exception(ex.Message);
            }
        }

        //get form document information
        public IEnumerable<object> getAllSmartChartAnswerDetails(object data)
        {
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    DynamicParameters param = new DynamicParameters();
                    // const string query = @"public.spgetdynamicformdashboarddetailsupdatedmultiple";
                    const string query = @"public.spgetdynamicsmartchartanswer";
                    var jsonstr = JsonConvert.SerializeObject(data);
                    param.Add("inputjsonstr", jsonstr);
                    param.Add("mode_p", "getallform");
                    dbConnection.Open();
                    return dbConnection.Query<object>(query, param, commandTimeout: 0, commandType: CommandType.StoredProcedure);
                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                throw new Exception(ex.Message);
            }
        }

        //get form document information
        public IEnumerable<object> getSmartChartAnswerRenderDetails(object data)
        {
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    DynamicParameters param = new DynamicParameters();
                    // const string query = @"public.spgetdynamicformdashboarddetailsupdatedmultiple";
                    const string query = @"public.spgetdynamicsmartchartanswer";
                    var jsonstr = JsonConvert.SerializeObject(data);
                    param.Add("inputjsonstr", jsonstr);
                    param.Add("mode_p", "formrender");
                    dbConnection.Open();
                    return dbConnection.Query<object>(query, param, commandTimeout: 0, commandType: CommandType.StoredProcedure);
                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                throw new Exception(ex.Message);
            }
        }

        public int updateSmartChartData(object data, string formconfigid, string tablename)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                int result = 0;
                string query = @"public.spsmartchartformrender";
                dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(data.ToString());
                string input = Newtonsoft.Json.JsonConvert.SerializeObject(json);
                var param = new DynamicParameters();
                param.Add("inputjsonstr", input);
                param.Add("mode_p", "update");
                result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();
                //code to add user activity log 
                if (result != 0)
                {
                    useractivitylogModel userlogmodel;
                    userlogmodel = new useractivitylogModel();
                    userlogmodel.useraction = "update Smart Chart Data  Form Render information";
                    userlogmodel.description = "update Smart Chart Data Form Render information.Added id is" + result + " in the table " + tablename;
                    oCommonRepository.useractivityAdd(userlogmodel);
                }

                return result;
            }
        }

        public int deactiveSmartChartAnswerDetails(object data)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                int result = 0;
                string query = @"public.spsmartchartformrender";
                //  dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(data.ToString());
                string input = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                var param = new DynamicParameters();
                param.Add("inputjsonstr", input);
                param.Add("mode_p", "deactive");
                result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();
                //code to add user activity log 
                if (result != 0)
                {
                    useractivitylogModel userlogmodel;
                    userlogmodel = new useractivitylogModel();
                    userlogmodel.useraction = "deactive Smart Chart Data  Form Render information";
                    userlogmodel.description = "deactive Smart Chart Data Form Render information.Added id is" + result;
                    oCommonRepository.useractivityAdd(userlogmodel);
                }

                return result;
            }
        }

        public object getEditorDisplayStatusByID(int id)
        {
            // bool result = false;
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spsmartchartdisplayseqselect";
                param.Add("smartchartconfigid_p", id);
                return dbConnection.Query<object>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        public object GetAllSmartChartAnswers(object data)
        {
            //bool result = false;
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    // dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(data.ToString());
                    string input = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                    var param = new DynamicParameters();
                    const string query = @"spgetdynamicsmartchartanswer";
                    param.Add("inputjsonstr", input);
                    param.Add("mode_p", "getall");
                    return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                throw new Exception(ex.Message);
            }

        }

        public object GetAllSmartChartAnswersCount(object data)
        {
            //bool result = false;
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    // dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(data.ToString());
                    string input = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                    var param = new DynamicParameters();
                    const string query = @"spgetsmartchartconfigrowcount";
                    param.Add("inputjsonstr", input);
                    param.Add("mode_p", "getall");
                    return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                throw new Exception(ex.Message);
            }

        }
        public int updateAllSmartChartData(object data)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                int result = 0;
                string query = @"public.spsmartchartupdateall";
                dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(data.ToString());
                string input = Newtonsoft.Json.JsonConvert.SerializeObject(json);
                var param = new DynamicParameters();
                param.Add("inputjsonstr", input);
                param.Add("mode_p", "updateall");
                result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();
                //code to add user activity log 
                if (result != 0)
                {
                    useractivitylogModel userlogmodel;
                    userlogmodel = new useractivitylogModel();
                    userlogmodel.useraction = "update Smart Chart Data  Form Render information";
                    userlogmodel.description = "update Smart Chart Data Form Render information.Added id is" + result + " in the table ";
                    oCommonRepository.useractivityAdd(userlogmodel);
                }

                return result;
            }
        }
    }
}
