using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unibase.Data;
using Unibase.Data.Enums;
using Unibase.Data.Expressions;
using Unibase.Dependency;
using Unibase.Platform.Data;
using Unibase.Platform.DataSources.Attributes;
using Unibase.Platform.Managers;
using Unibase.Data.Sql;

namespace Bizgaze.CRM.Visitors.Managers
{
    internal partial class VisitorManager : BaseManager, IVisitorManager
    {
        #region Getting data By VisitorId
        public async Task<SelectResponse<Infos.Visitor>> GetVisitorByIdAsync(SelectRequest request, long VisitorId)
        {
            var exp = request.Filter();
            exp = exp & Unibase.Data.Expressions.Exp.Eq(Infos.Visitor.Property.VisitorId.ToString(), VisitorId);
            request.Filter(exp);
            var data = await GetSingleAsync<Infos.Visitor>(request);
            return data;
        }
        #endregion

        #region Get Visitors html

        [SelectMethod(ApiName = "Get visitors Html", AppName = "crm", Description = "Get visitors Html", UniqueName = "bizgaze_transact_visitors_GetvisitorsHtml", MethodName = "getvisitorshtml", ModuleName = "visitors", PackageName = "bizgaze", ParamName1 = "visitorid")]
        public async Task<SelectResponse<Unibase.Platform.Templates.Infos.PrintTemplate>> GetVisitorshtmlAsync(SelectRequest srequest, long VisitorId)
        {

            long templateid = 0;
            //var appManager = Unibase.Dependency.DependencyConfig.Resolve<Unibase.Platform.Apps.Managers.IAppManager>();
            var templateManager = Unibase.Dependency.DependencyConfig.Resolve<Unibase.Platform.Templates.Managers.ITemplateManager>();
            var templateInfos = await templateManager.GetTemplatesAsync(srequest, "Bizgaze_Extension_CRM_CRM_TemplateProvider_Visitors");
            if (templateInfos.Result != null && templateInfos.Result.Count > 0)
            {
                templateid = templateInfos.Result[0].TemplateId;
            }
            var result = new SelectResponse<Unibase.Platform.Templates.Infos.PrintTemplate>();
            var printTemplate = new Unibase.Platform.Templates.Infos.PrintTemplate();
            //var templateManager = //Unibase.Dependency.DependencyConfig.Resolve<Unibase.Platform.Templates.Managers.ITemplateManager>();
            var VisitorInfo_ = await GetVisitorByIdAsync(srequest, VisitorId);
            var visitor = VisitorInfo_.Result.VisitorId;
            var _dbContext = DependencyConfig.Resolve<Unibase.Data.IDbContext>();
            Unibase.Platform.Templates.Helpers.TemplateHelper helper = new Unibase.Platform.Templates.Helpers.TemplateHelper(_dbContext);
            List<Parameter> param = new List<Parameter>();
            var select = new Unibase.Data.Sql.Select().AllColumns().From("bizgazecrm_visitors").Where("visitorid", visitor);
            param.Add(new Parameter("visitorid", visitor));
            var dt = await GetDataTableAsync(srequest, select, param);
            var exp = srequest.Filter();
            exp = exp & Unibase.Data.Expressions.Exp.Eq(Infos.Visitor.Property.VisitorId.ToString(), visitor);
            srequest.Filter(exp);
            var data = await GetSingleAsync<Infos.Visitor>(srequest);
            if (data.Result == null)
            {
                return SelectResponse<Unibase.Platform.Templates.Infos.PrintTemplate>.CreateErrorResponse("1", "visitor  Not Found");
            }
            // var templateId = 0;  
            srequest.Filter(null);
            var tInfo = await templateManager.GetTemplateAsync(srequest, templateid);
            var templateInfo = tInfo.Result;
            if (templateInfo == null)
                return SelectResponse<Unibase.Platform.Templates.Infos.PrintTemplate>.CreateErrorResponse("1", "Template Not Found");
            var DefaultTokens = new Dictionary<string, string>();
            var template = System.Web.HttpUtility.UrlDecode(templateInfo.TemplateText.ToString());
            // var template = helper.GetTemplatedText(srequest, templateText, DefaultTokens, dt.Rows[0]);
            string multiTemplateText = "";
            var tabletemp = "";
            foreach (DataRow row in dt.Rows)
            {
                var Name = row["fullname"].ToString();
                var ComingFrom = row["ComingFrom"].ToString();
                //var Purposeofvisit = row["PurposeOfVisit"].ToString();
                var MobileNumber = row["MobileNumber"].ToString();
                var HostPerson = data.Result.HostName;
                var photoUrl = row["PhotoUrl"].ToString();
                var Code = row["Code"];
                var CreatedDate = row["CreatedDate"].ToString();
                var Purposeofvisit = data.Result.PurposeOfVisitType;
                if (template.Contains("{{fullname}}"))
                {
                    template = template.Replace("{{fullname}}", Name.ToString());
                }
                if (template.Contains("{{comingfrom}}"))
                {
                    template = template.Replace("{{comingfrom}}", ComingFrom.ToString());
                }
                if (template.Contains("{{purposeofvisit}}"))
                {
                    template = template.Replace("{{purposeofvisit}}", Purposeofvisit.ToString());
                }
                if (template.Contains("{{phonenumber}}"))
                {
                    template = template.Replace("{{phonenumber}}", MobileNumber.ToString());
                }
                if (template.Contains("{{code}}"))
                {
                    template = template.Replace("{{code}}", Code.ToString());
                }
                if (template.Contains("{{createddate}}"))
                {
                    template = template.Replace("{{createddate}}", CreatedDate.ToString());
                }
                if(template.Contains("{{photourl}}"))
                {
                    template = template.Replace("{{photourl}}", photoUrl.ToString());
                }
                if (template.Contains("{{HostName}}"))
                {
                    template = template.Replace("{{HostName}}", HostPerson.ToString());
                }
                multiTemplateText = template;
            }
            printTemplate.PrintHTML = multiTemplateText;
            printTemplate.FileName = "Visitors";
            printTemplate.PkId = VisitorId;
            result.Result = printTemplate;
            return result;
            //return await GetSingleAsync<Infos.Visitor>(srequest);

        }
        #endregion

        #region Get Pre_Visitors

        [SelectMethod(ApiName = "Get  pre visitors", AppName = "crm", Description = "Get pre visitors", UniqueName = "bizgaze_transact_visitors_Getprevisitors", MethodName = "Getprevisitors", ModuleName = "visitors", PackageName = "bizgaze", ParamName1 = "code")]
        public async Task<SelectResponse<Bizgaze.CRM.Visitors.Infos.Visitor>> GetpreVisitorsAsync(SelectRequest srequest, string code)
        {
            var exp = srequest.Filter();
            exp &= Exp.Eq(Bizgaze.CRM.Visitors.Infos.Visitor.Property.Code.ToString(), code);
            srequest.Filter(exp);
            var visData = await GetSingleAsync<Bizgaze.CRM.Visitors.Infos.Visitor>(srequest);

            if (visData.Result != null)
            {
                var refStatusId = visData.Result.RefStatusId;
                if (refStatusId != 2)
                {
                    return visData;

                }
            }
            else
            {
                return SelectResponse<Bizgaze.CRM.Visitors.Infos.Visitor>.CreateErrorResponse("404", "Please Enter A Valid Uniqueid!");

            }
            return SelectResponse<Bizgaze.CRM.Visitors.Infos.Visitor>.CreateErrorResponse("404", "you have been already checked out");

        }
        #endregion

        #region Visitor Agreement
        [ActionMethod(ApiName = "visitor agreement", AppName = "crm", Description = "visitor agreement", UniqueName = "bizgaze_transact_visitors_visitoragreement", MethodName = "visitoragreement", ModuleName = "visitors", PackageName = "bizgaze", ParamName1 = "visitorid")]
        public async Task<ActionResponse<Bizgaze.CRM.Visitors.Infos.Visitor>> VisitorAgreementAsync(ActionRequest arequest, long VisitorId)
        {
            var srequest = SelectRequest.FromRequest(arequest);
            var parameters = new List<Unibase.Data.Parameter>();
            var connection = GetConnection(srequest);
            var visitorinfo = await GetVisitorsAsync(srequest, VisitorId);
            if (visitorinfo.Result != null)
            {
                parameters.Add(new Unibase.Data.Parameter("@visitorid", VisitorId));
                var Agreementupdate = "update bizgazecrm_visitors set agreement=" + "true" + " where visitorid=" + visitorinfo.Result.VisitorId;
                var sqlvoucher = await _dbContext.ExecuteAsync(connection, Agreementupdate, Unibase.Data.Enums.InstructionType.Query, parameters); return ActionResponse<Bizgaze.CRM.Visitors.Infos.Visitor>.CreateSuccessResponse("Agreement Success", null);
            }
            else
            {
                return ActionResponse<Bizgaze.CRM.Visitors.Infos.Visitor>.CreateErrorResponse("", "Visitor Not Found");
            }
            
        }

        #endregion

        #region check Mobile Number

        [ActionMethod(ApiName = "check Mobile Number", AppName = "crm", Description = "check Mobile Numbert", UniqueName = "bizgaze_transact_visitors_checkMobileNumber", MethodName = "checkmobilenumber", ModuleName = "visitors", PackageName = "bizgaze", ParamName1 = "mobilenumber",ParamName2 ="emailid")]
        public async Task<ActionResponse<Bizgaze.CRM.Visitors.Infos.Visitor>>checkMobileNumberAsync(ActionRequest arequest, string mobileNumber ,string emailId)
        {
            var srequest = SelectRequest.FromRequest(arequest);
            var parameters = new List<Unibase.Data.Parameter>();
            var connection = GetConnection(srequest);
            var sql = new Unibase.Data.Sql.Select("bizgazecrm_visitors").AllColumns();
            List<Unibase.Data.Parameter> viparam = new List<Unibase.Data.Parameter>();
            return ActionResponse<Bizgaze.CRM.Visitors.Infos.Visitor>.CreateErrorResponse("", "Mobile Number And Email Id Alredy Exit");          
        }

        #endregion

        #region  Getting data from Visitors by Mobile Number
        [SelectMethod(ApiName = "getvisitorsbymobilenumber", AppName = "crm", Description = "getvisitorsbymobilenumber", UniqueName = "bizgaze_transact_visitors_getvisitorsbymobilenumber", MethodName = "visitorsbymobilenumber", ModuleName = "visitors", PackageName = "bizgaze", ParamName1 = "mobilenumber")]
        public async Task<SelectResponse<Bizgaze.CRM.Visitors.Infos.Visitor>> VisitorsbyMobileNumberAsync(SelectRequest srequest, string MobileNumber)
        {
            var exp = srequest.Filter();
            exp = exp & Exp.Eq(Bizgaze.CRM.Visitors.Infos.Visitor.Property.MobileNumber.ToString(), MobileNumber);
            srequest.Filter(exp);
            return await GetSingleAsync<Bizgaze.CRM.Visitors.Infos.Visitor>(srequest);
        }
        #endregion

        #region  Get installedAppId Async

        [SelectMethod(ApiName = "getinstallappid", AppName = "crm", Description = "getinstallappid", UniqueName = "bizgaze_crm_visitors_getinstallappid", MethodName = "getinstallappid", ModuleName = "visitors", PackageName = "bizgaze", ParamName1 = "visitorid")]
        public async Task<SelectResponse<Bizgaze.CRM.Visitors.Infos.Visitor>> GetInstallappAsync(SelectRequest srequest, long VisitorId)
        {
            var exp = srequest.Filter();
            exp = exp & Exp.Eq(Bizgaze.CRM.Visitors.Infos.Visitor.Property.VisitorId.ToString(), VisitorId);
            srequest.Filter(exp);
            return await GetSingleAsync<Bizgaze.CRM.Visitors.Infos.Visitor>(srequest);
        }
        #endregion

        #region Get Visitor INformation

        public async Task<SelectResponse<Bizgaze.CRM.Visitors.Infos.Visitor>> GetVisitorsAsync(SelectRequest srequest, long VisitorId)
        {
            var exp = srequest.Filter();
            exp &= Exp.Eq(Bizgaze.CRM.Visitors.Infos.Visitor.Property.VisitorId.ToString(), VisitorId);
            srequest.Filter(exp);
            return await GetSingleAsync<Bizgaze.CRM.Visitors.Infos.Visitor>(srequest);
        }

        #endregion

        #region Save Visitor Image
        [ActionMethod(ApiName = "VisitorCapture ", AppName = "crm", Description = "image Capture ", UniqueName = "Bizgaze_crm_Visitor_Capture", MethodName = "SaveVisitorImage", ModuleName = "visitors", PackageName = "bizgaze")]
        public ActionResponse SaveVisitorImageAsync(ActionRequest request, ExpandoObject obj)
        {
            using (var requestTrans = request.BeginTransaction())
            {
                {
                    SelectRequest rrequest = new SelectRequest(request.Transaction)
                    {
                        Identity = request.Identity
                    };
                    var dictObj = obj as IDictionary<string, dynamic>;
                    var visitorid = Convert.ToInt64(dictObj["visitorid"].ToString());
                    var Photourl = dictObj["image"].ToString();
                    var parameters = new Dictionary<string, object>();
                    var Update = new Update("bizgazecrm_visitors");
                    parameters.Add("photourl", Photourl);
                    Update.Values(parameters).Where(Exp.Eq("visitorid", visitorid));
                    var ds = _repository.Execute(request, Update); 
                    if (requestTrans.StartedLocal) request.CommitTransaction();
                    return ActionResponse.CreateSuccessResponse("Your Image Saved Successfully", ds.Result);                   
                }
                
            }
        }

        #endregion

    }
}

