using Bizgaze.CRM;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unibase.Data;
using Unibase.Data.Expressions;
using Unibase.Data.Sql;
using Unibase.Dependency;
using Unibase.Platform.Apps.Managers;
using Unibase.Platform.Data;
using Unibase.Platform.Forms.Providers;
using Unibase.Platform.Keys;

namespace Bizgaze.CRM.Visitors.ActionProviders
{
    public class VisitorStageChangeAndUpDateContacts : BaseFormActionProvider, IFormActionProvider
    {
        public string ControllerClass
        {
            get
            {
                return "Bizgaze.CRM.Visitors.ActionProviders.VisitorStageChangeAndUpDateContacts";

            }
        }
        public string FormActionName
        {
            get
            {
                return "VisitorStageChangeAndUpDateContacts";
            }
        }
        public string Description
        {
            get
            {
                return "Visitor Stage Change And UpDate Contacts";
            }
        }
        public UniqueKey UniqueId
        {
            get
            {
                return Bizgaze.CRM.Actions.VisitorStageChangeAndUpDateContacts;
            }
        }
        public int ActionType
        {
            get
            {
                return (int)Unibase.Platform.Forms.Enums.FormActionProvider.PostAction;
            }
        }
        //public ActionResponse<ExpandoObject> Execute(ActionRequest request, object IdValue, ExpandoObject obj, List<Unibase.Platform.Forms.Requests.DocParameter> docParametersList, ref long defaultPKValue)
        //{
        //    return null;

        //}
        public async Task<ActionResponse<FormActionResponse>> ExecuteAsync(ActionRequest request, FormActionProviderObject providerObject)
        {
            using (var requestTrans = await request.BeginTransactionAsync())
            {
                var IdValue = providerObject.IdValue;
                var srequest = SelectRequest.FromRequest(request);
                var obj = providerObject.RequestObject;
                var docParametersList = providerObject.DocParametersList;
                dynamic visitorparam = new Dictionary<string, object>();
                var defaultPKValue = providerObject.DefaultPKValue;
                var stageManager = Unibase.Dependency.DependencyConfig.Resolve<IStageManager>();
                var dictObj = obj as IDictionary<string, dynamic>;
                List<Unibase.Platform.Forms.Requests.DocParameter> docParameters = dictObj["DocParameters"];
                var connection = GetConnection(request);
                ExpandoObject obj1 = dictObj["RequestObj"];
                var req = obj1 as IDictionary<string, object>;
                var visitorInfo = docParameters.Find(x => x.DocType == "bizgazecrm_visitors");
                if (visitorInfo != null)
                {
                    var visitorId = Convert.ToInt64(visitorInfo.Parameters["visitorid"]);
                    var visitorType = Convert.ToInt64(visitorInfo.Parameters["visitortype"]);
                    var sql = new Unibase.Data.Sql.Select("bizgazecrm_visitors").Columns("bizgazecrm_visitors.installedappid", "bizgazecrm_visitors.fullname", "bizgazecrm_visitors.mobilenumber", "bizgazecrm_visitors.emailid", "bizgazecrm_visitors.photourl", "unibase_stagestatus.stageStatusName", "unibase_stagestatus.RefStatusId").InnerJoin("unibase_stages", Exp.EqColumns("unibase_stages.stageid", "bizgazecrm_visitors.stageid")).InnerJoin("unibase_stagestatus", Exp.EqColumns("unibase_stagestatus.stagestatusid", "unibase_stages.stagestatusid")).Where("bizgazecrm_visitors.visitorid", visitorId);
                    List<Parameter> param = new List<Parameter>();
                    param.Add(new Parameter("@bizgazecrm_visitors.visitorid", visitorId));
                    var dt = GetDataTable(srequest, sql, param);
                    var mobileNumber = "";
                    var emailId = "";
                    long installedAppId = 0;
                    var visitorName = "";
                    var stageStatusName = "";
                    var photourl = "";
                    if (dt.Rows.Count > 0)
                    {
                        if (visitorType == 1)
                        {
                            stageStatusName = "CheckIn";
                        }
                        else
                        {
                            stageStatusName = "Pre-Invite";
                            defaultPKValue = visitorId;
                        }

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            mobileNumber = Convert.ToString(dt.Rows[i]["mobileNumber"]);
                            emailId = Convert.ToString(dt.Rows[i]["emailid"]);
                            installedAppId = Convert.ToInt64(dt.Rows[i]["installedAppId"]);
                            visitorName = Convert.ToString(dt.Rows[i]["fullname"]);
                            photourl = Convert.ToString(dt.Rows[i]["photourl"]);
                            var stage = stageManager.GetStageByStageStatus(srequest, installedAppId, stageStatusName);
                            var NewStageId = stage.Result.StageId;
                            var UpdateStage = new Update("bizgazecrm_visitors").Value("stageid", NewStageId).Where(Exp.Eq("visitorId", visitorId));
                            _repository.Execute(request, UpdateStage);

                        }
                    }
                    var visitorTypeid = Convert.ToInt64(visitorInfo.Parameters["visitortype"]);
                    if (visitorTypeid != 2)
                    {
                        var options1 = new EntityOptions()
                        {
                            IsIdentity = true,
                            IsNewEntity = true,
                            TableName = "unibasecmn_users",
                            PkColumn = "userid",
                            IsExcludeFromAudit = false,
                            Id = 0,
                        };
                        dynamic visitorparameters1 = new Dictionary<string, object>();

                        visitorparameters1.Add("username", visitorName);
                        visitorparameters1.Add("createdby", srequest.Identity.UserId);
                        visitorparameters1.Add("createddate", DateTime.Now);
                        visitorparameters1.Add("versionguid", Guid.NewGuid());
                        visitorparameters1.Add("statusid", (int)RowStatus.Active);
                        visitorparameters1.Add("installedappid", installedAppId);
                        visitorparameters1.Add("phonenumber", mobileNumber);
                        visitorparameters1.Add("emailaddress", emailId);

                        var responses = await _repository.SaveAsync(request, options1, visitorparameters1);
                        if (responses.Status == ResponseStatus.Error)
                        {
                            if (requestTrans.StartedLocal) await request.RollbackTransactionAsync();
                            return ActionResponse<FormActionResponse>.CreateErrorResponse("1", "user Are Not Saved");
                        }
                        else
                        {
                            
                            using (var requestTrans1 = await request.BeginTransactionAsync())
                            {
                                Int64 userid =0;
                                {
                                    var data = responses.Result as Dictionary<string, object>;
                                    userid = Convert.ToInt64(data["_Id"]);
                                }
                                var options = new EntityOptions()
                                {
                                    IsIdentity = false,
                                    IsNewEntity = true,
                                    TableName = "bizgazecrm_contacts",
                                    PkColumn = "contactid",
                                    IsExcludeFromAudit = false,
                                    Id = 0,
                                };
                                dynamic contactparameters = new Dictionary<string, object>();
                                contactparameters.Add("contactid", userid);
                                contactparameters.Add("contactname", visitorName);
                                contactparameters.Add("photourl", photourl);
                                contactparameters.Add("createdby", srequest.Identity.UserId);
                                contactparameters.Add("createddate", DateTime.Now);
                                contactparameters.Add("versionguid", Guid.NewGuid());
                                contactparameters.Add("statusid", (int)RowStatus.Active);
                                contactparameters.Add("installedappid", installedAppId);

                                var response = await _repository.SaveAsync(request, options, contactparameters);
                                if (response.Status == ResponseStatus.Error)
                                {
                                    if (requestTrans.StartedLocal) await request.RollbackTransactionAsync();
                                    return ActionResponse<FormActionResponse>.CreateErrorResponse("1", "Contacts Are Not Saved");
                                }

                                var update = new Update("bizgazecrm_visitors").Value("contactid", userid).Where(Exp.Eq("visitorid", visitorId));
                                await _repository.ExecuteAsync(request, update);

                            }
                        }
                    }
                }

                var returnresponse = new FormActionResponse();
                returnresponse.Obj = dictObj as ExpandoObject;
                returnresponse.PkValue = defaultPKValue;
                return ActionResponse<FormActionResponse>.CreateSuccessResponse("success", returnresponse);
            }
        }

        public List<UniqueKey> AppliedApps
        {
            get
            {
                return new List<UniqueKey>() {
                    Bizgaze.CRM.Actions.VisitorStageChangeAndUpDateContacts,
            };
            }
        }

    }
}
