using Dapper;
using Newtonsoft.Json;
using System;
using System.Data;
using System.Linq;
using WK_KLI_LAPS_Service.Models.Master;

namespace WK_KLI_LAPS_Service.App_Data
{
    public class UserRepository
    {
        CommonRepository oCommonRepository = new CommonRepository();
        public void Add(userModel item, string mode)
        {
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    DynamicParameters param = new DynamicParameters();
                    var jsonstr = JsonConvert.SerializeObject(item);
                    param.Add("inputjsonstr", jsonstr);
                    param.Add("mode_p", mode);
                    int res = dbConnection.Query<int>("public.spusermaster", param, commandType: CommandType.StoredProcedure).FirstOrDefault();

                    if (mode == "insert")
                    {
                        param = new DynamicParameters();
                        param.Add("userid_p", res);
                        param.Add("passwordhash_p", item.passwordhash);
                        param.Add("passwordsalt_p", item.passwordsalt);

                        dbConnection.Query<userModel>("spusermasterupdatepassword", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                    }
                    //code to add user activity log
                    if (res != 0)
                    {
                        useractivitylogModel userlogmodel;
                        userlogmodel = new useractivitylogModel();
                        if (mode == "insert")
                        {
                            userlogmodel.useraction = "Add User";
                            userlogmodel.description = "Added User";
                        }
                        else
                        {
                            userlogmodel.useraction = "User request";
                            userlogmodel.description = "User request added";
                        }

                        oCommonRepository.useractivityAdd(userlogmodel);
                    }
                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                throw;
            }

        }



        public object FindAll()
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                DynamicParameters param = new DynamicParameters();
                param.Add("mode_p", "getallusers");
                dbConnection.Open();
                return dbConnection.Query<string>("spusermasterselect", param, commandType: CommandType.StoredProcedure);


            }
        }
        public object FindByID(int id)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                DynamicParameters param = new DynamicParameters();
                var user = new { userid_p = id };
                var jsonstr = JsonConvert.SerializeObject(user);
                param.Add("inputjsonstr", jsonstr);
                param.Add("mode_p", "getbyid");
                dbConnection.Open();
                return dbConnection.Query<string>("spusermasterselect", param, commandType: CommandType.StoredProcedure);
            }
        }

        public userModel FindByEmail(string email)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                DynamicParameters param = new DynamicParameters();
                param.Add("userid_p",null);
                param.Add("username_p", null);
                param.Add("email_p", email);
                dbConnection.Open();
                return dbConnection.Query<userModel>("sploginselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();

            }

        }

        public userModel FindByName(string name)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                DynamicParameters param = new DynamicParameters();
                param.Add("userid_p", null);
                param.Add("username_p", name);
                param.Add("email_p", null);
                dbConnection.Open();
                return dbConnection.Query<userModel>("sploginselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();

            }
        }
        public void Remove(userModel user)
        {

            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    DynamicParameters param = new DynamicParameters();
                    var jsonstr = JsonConvert.SerializeObject(user);
                    param.Add("inputjsonstr", jsonstr);
                    param.Add("mode_p", "activeordeactive");
                    var res = dbConnection.Query<int>("public.spusermaster", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                    //code to update user activity log
                    if (res != 0)
                    {
                        useractivitylogModel userlogmodel;
                        userlogmodel = new useractivitylogModel();
                        userlogmodel.useraction = "Active/inactive User";
                        userlogmodel.description = "Active/inactive User";

                        oCommonRepository.useractivityAdd(userlogmodel);
                    }
                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                throw;
            }


        }

        public void Update(userModel item, string mode)
        {
            if (mode.ToString().Equals("resetpassword"))
            {
                userModel user = new userModel();
                user = (userModel)FindByEmail(item.emailid);
                if (user != null)
                    item.userid = user.userid;
            }

            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                if (mode.ToString().Equals("resetpassword") || mode.ToString().Equals("changepassword"))
                {
                    DynamicParameters param = new DynamicParameters();
                    param.Add("userid_p", item.userid);
                    param.Add("passwordhash_p", item.passwordhash);
                    param.Add("passwordsalt_p", item.passwordsalt);
                    dbConnection.Open();
                    int res = dbConnection.Query<int>("spusermasterupdatepassword", param, commandType: CommandType.StoredProcedure).FirstOrDefault();

                    //code to update user activity log
                    if (res != 0)
                    {
                        useractivitylogModel userlogmodel;
                        userlogmodel = new useractivitylogModel();
                        userlogmodel.useraction = "Password change";
                        userlogmodel.description = "Password changed";

                        oCommonRepository.useractivityAdd(userlogmodel);
                    }
                }


                if (mode.ToString().Equals("updateuser"))
                {
                    try
                    {
                        dbConnection.Open();
                        DynamicParameters param = new DynamicParameters();
                        var jsonstr = JsonConvert.SerializeObject(item);
                        param.Add("inputjsonstr", jsonstr);
                        param.Add("mode_p", "update");
                        int res = dbConnection.Query<int>("public.spusermaster", param, commandType: CommandType.StoredProcedure).FirstOrDefault();


                        //code to update user activity log
                        if (res != 0)
                        {

                            userModel user = new userModel();
                            user = (userModel)FindByEmail(item.emailid);
                            if (user != null)
                            {

                                if ((item.singlesignon != 1 || item.accessrequestid != 0) && (user.passwordsalt == null))
                                {
                                    param = new DynamicParameters();
                                    param.Add("userid_p", res);
                                    param.Add("passwordhash_p", item.passwordhash);
                                    param.Add("passwordsalt_p", item.passwordsalt);
                                    dbConnection.Query<userModel>("spusermasterupdatepassword", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                                }
                            }





                            useractivitylogModel userlogmodel;
                            userlogmodel = new useractivitylogModel();
                            userlogmodel.useraction = "Update user";
                            userlogmodel.description = "User updated";

                            oCommonRepository.useractivityAdd(userlogmodel);
                        }



                    }
                    catch (Exception ex)
                    {
                        oCommonRepository.ErrorLog(ex);
                        throw;
                    }
                }
                if (mode.ToString().Equals("requestapprove"))
                {
                    try
                    {
                        dbConnection.Open();
                        DynamicParameters param = new DynamicParameters();
                        var jsonstr = JsonConvert.SerializeObject(item);
                        param.Add("inputjsonstr", jsonstr);
                        param.Add("mode_p", "requestapprove");
                        int res = dbConnection.Query<int>("public.spusermaster", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                        //code to update user activity log
                        if (res != 0)
                        {
                            useractivitylogModel userlogmodel;
                            userlogmodel = new useractivitylogModel();
                            userlogmodel.useraction = "Request Approve";
                            userlogmodel.description = "Request Approved";

                            oCommonRepository.useractivityAdd(userlogmodel);
                        }

                    }
                    catch (Exception ex)
                    {
                        oCommonRepository.ErrorLog(ex);
                        throw;
                    }
                }
            }
        }





        public loginhistoryModel FindByLoginId(Int64 loginid)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                DynamicParameters param = new DynamicParameters();
                param.Add("logid_p", loginid);
                param.Add("userid_p", null);
                dbConnection.Open();

                return dbConnection.Query<loginhistoryModel>("sploginhistoryselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();

            }
        }


        public Int64 UpdateLoginHistory(Int64 logid)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                DynamicParameters param = new DynamicParameters();
                var user = new { logid_p = logid };
                var jsonstr = JsonConvert.SerializeObject(user);
                param.Add("inputjsonstr", jsonstr);
                param.Add("mode_p", "update");
                dbConnection.Open();
                return dbConnection.Execute("sploginhistory", param, commandType: CommandType.StoredProcedure);
            }
        } 
        public Int64 UpdatePendinglots(Int64 userid)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                DynamicParameters param = new DynamicParameters();
                var user = new { userid_p = userid };
                var jsonstr = JsonConvert.SerializeObject(user);
                param.Add("inputjsonstr", jsonstr);
                param.Add("mode_p", "pendinglots");
                dbConnection.Open();
                return dbConnection.Execute("sploginhistory", param, commandType: CommandType.StoredProcedure);
            }
        }

        public Int64 Addloginhistory(loginhistoryModel item)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {

                DynamicParameters param = new DynamicParameters();
                var user = new { userid_p = item.Userid, ipaddress_p = item.ipaddress };
                var jsonstr = JsonConvert.SerializeObject(user);
                param.Add("inputjsonstr", jsonstr);
                param.Add("mode_p", "insert");
                param.Add("@returnid", dbType: DbType.Int64, direction: ParameterDirection.Output);
                dbConnection.Open();
                dbConnection.Execute("sploginhistory", param, commandType: CommandType.StoredProcedure);
                Int64 returnid = param.Get<Int64>("@returnid");
                return returnid;
            }

        }


        public bool FindbyMailidForUser(string mailid)
        {
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    DynamicParameters param = new DynamicParameters();
                    var user = new { email_p = mailid };
                    var jsonstr = JsonConvert.SerializeObject(user);
                    param.Add("inputjsonstr", jsonstr);
                    param.Add("mode_p", "checkemailexists");
                    dbConnection.Open();
                    var _list = dbConnection.Query<string>("spusermasterselect", param, commandType: CommandType.StoredProcedure).ToList();
                    if (_list.Count() > 0 && _list.ToList()[0] != null)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }

                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                throw;
            }
        }
        public bool FindbyMailidForUserUpdate(string mailid, int userid)
        {
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    DynamicParameters param = new DynamicParameters();
                    var user = new { userid_p = userid, email_p = mailid };
                    var jsonstr = JsonConvert.SerializeObject(user);
                    param.Add("inputjsonstr", jsonstr);
                    param.Add("mode_p", "checkemailexists");
                    dbConnection.Open();
                    var _list = dbConnection.Query<string>("spusermasterselect", param, commandType: CommandType.StoredProcedure).ToList();
                    if (_list.Count() > 0 && _list.ToList()[0] != null)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }

                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                throw;
            }
        }
        public object FindByIdForUser(int id)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                DynamicParameters param = new DynamicParameters();
                var user = new { userid_p = id };
                var jsonstr = JsonConvert.SerializeObject(user);
                param.Add("inputjsonstr", jsonstr);
                param.Add("mode_p", "getbyid");
                dbConnection.Open();
                return dbConnection.Query<object>("spusermasterselect", param, commandType: CommandType.StoredProcedure);

            }
        }



        public object FindActiveUsers()
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                DynamicParameters param = new DynamicParameters();
                param.Add("inputjsonstr", null);
                param.Add("mode_p", "getactiveuser");
                dbConnection.Open();
                return dbConnection.Query<string>("spusermasterselect", param, commandType: CommandType.StoredProcedure);


            }
        }



        // Get the list of all master data present in the db
        public object GetByRoleId(string inputjsonval)
        {

            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = @"public.spusermasterselect";
                param.Add("inputjsonstr", inputjsonval);
                param.Add("mode_p", dbType: DbType.String, value: "getbyrole", direction: ParameterDirection.Input);
                var _list = dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
                return _list;

            }
        }

        public object GetUsersByDepartment(int departmentid)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                DynamicParameters param = new DynamicParameters();
                var user = new { departmentid = departmentid };
                var jsonstr = JsonConvert.SerializeObject(user);
                param.Add("inputjsonstr", jsonstr);
                param.Add("mode_p", "getusersbydepartment");
                dbConnection.Open();
                return dbConnection.Query<string>("spusermasterselect", param, commandType: CommandType.StoredProcedure);
            }
        }
        public object GetserRights(int userid)
        {
            object result = String.Empty;
            try
            {

                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    var user = new { userid_p = userid };
                    DynamicParameters param = new DynamicParameters();
                    var jsonstr = JsonConvert.SerializeObject(user);
                    param.Add("inputjsonstr", jsonstr);
                    param.Add("mode_p", "getuserrights");
                    dbConnection.Open();
                    result = dbConnection.Query<string>("spusermasterselect", param, commandType: CommandType.StoredProcedure);
                }
                return result;
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return result;
            }

        }
        public object Getuserpendinglotinfo(int userid)
        {
            object result = String.Empty;
            try
            {

                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    var user = new { userid_p = userid };
                    DynamicParameters param = new DynamicParameters();
                    var jsonstr = JsonConvert.SerializeObject(user);
                    param.Add("inputjsonstr", jsonstr);
                    param.Add("mode_p", "getuserpendinglot");
                    dbConnection.Open();
                    result = dbConnection.Query<string>("spusermasterselect", param, commandType: CommandType.StoredProcedure);
                }
                return result;
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return result;
            }

        }


        //gokul added 01-02-2023
        public object Master_MailFollderMapping(string spname, string inputjson, string mode_p)
        {
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    string query = spname;
                    var param = new DynamicParameters();
                    param.Add("mode_p", dbType: DbType.String, value: mode_p, direction: ParameterDirection.Input);
                    if(inputjson != "")
                    {
                        param.Add("inputjsonstr", dbType: DbType.String, value: inputjson, direction: ParameterDirection.Input);
                    }
                    return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).First();

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
