using FI.FIC.Contracts.DataObjects.BaseObject;
using Foresight.Fleet.Services.Credentials;
using Foresight.Fleet.Services.Credentials.JDAPI;
using Foresight.Service.Credential.Common;
using Foresight.Service.Credential.JDAPI;
using Foresight.ServiceModel;
using IronIntel.Contractor.Users;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace IronIntel.Contractor.Site.Credentials
{
    public class CredentialEntryBasePage : ContractorBasePage
    {
        private const string AEMP = "AEMPFLEET";
        private const string JDAPI = "JDAPI";
        protected void ProcessRequest(string methodName)
        {
            if (methodName != null)
            {
                switch (methodName)
                {
                    case "GetAEMPCredentials":
                        GetAEMPCredentials();
                        break;
                    case "UpdateAEMPCredential":
                        UpdateAEMPCredential();
                        break;
                    case "DeleteAEMPCredential":
                        DeleteAEMPCredential();
                        break;
                    case "DeleteToken":
                        DeleteToken();
                        break;
                    case "GetJDLinkTokenItems":
                        GetJDLinkTokenItems();
                        break;
                    case "CreateJDLinkAuthUrl":
                        CreateJDLinkAuthUrl();
                        break;
                    case "GetAPIDictionaries":
                        GetAPIDictionaries();
                        break;
                    case "GetAPICredentialDefs":
                        GetAPICredentialDefs();
                        break;
                    case "UpdateApiCredentialDefs":
                        UpdateApiCredentialDefs();
                        break;
                    case "DeleteApiCredential":
                        DeleteApiCredential();
                        break;
                    case "GetNotificationSubscriptions":
                        GetNotificationSubscriptions();
                        break;
                    case "CreateJDSubPubAuthUrl":
                        CreateJDSubPubAuthUrl();
                        break;
                    case "DeleteNotificationSubscription":
                        DeleteNotificationSubscription();
                        break;
                    case "GetMyJDAPITokenItems":
                        GetMyJDAPITokenItems();
                        break;
                    case "CreateMyJDAPIAuthUrl":
                        CreateMyJDAPIAuthUrl();
                        break;
                    case "GetOrganizations":
                        GetOrganizations();
                        break;
                    case "GetJDOrganizationUrl":
                        GetJDOrganizationUrl();
                        break;
                }
            }

            Response.End();
        }

        protected override bool AllowCurrentLoginSessionEnter()
        {
            var f = base.AllowCurrentLoginSessionEnter();
            if (!f)
            {
                return false;
            }

            // check whether you are admin.
            var session = GetCurrentLoginSession();
            if (session == null || session.User == null)
            {
                return false;
            }
            var ui = UserManagement.GetUserByIID(session.User.UID);
            return ui != null && ui.UserType >= UserTypes.Admin;
        }

        #region  AEMP credential
        private void GetAEMPCredentials()
        {
            CredentialProvider crd = FleetServiceClientHelper.CreateClient<CredentialProvider>();
            AEMPInfo[] items = crd.GetAEMPCredentials(SystemParams.CompanyID);
            if (items == null)
                items = new AEMPInfo[0];

            items = items.OrderBy((c) => c.UserName).ToArray();
            string json = JsonConvert.SerializeObject(items);
            Response.Write(json);
            Response.End();
        }

        private void UpdateAEMPCredential()
        {
            var content = Request.Form["ClientData"];
            content = HttpUtility.HtmlDecode(content);
            var aempinfo = JsonConvert.DeserializeObject<AEMPInfo>(content);

            try
            {
                if (string.IsNullOrEmpty(aempinfo.ID))
                    aempinfo.ID = Guid.NewGuid().ToString();

                CredentialProvider crd = FleetServiceClientHelper.CreateClient<CredentialProvider>();
                crd.UpdateAEMPCredential(SystemParams.CompanyID, aempinfo);

            }
            catch (Exception ex)
            {
                Response.Write(JsonConvert.SerializeObject(ex.Message));
                return;
            }

            Response.Write("\"OK\"");
        }

        private void DeleteAEMPCredential()
        {
            var iid = Request.Form["ClientData"];
            Guid guid;
            if (!Guid.TryParse(iid, out guid))
            {
                throw new ArgumentException("Credential IID is not valid.");
            }
            CredentialProvider crd = FleetServiceClientHelper.CreateClient<CredentialProvider>();
            crd.DeleteAEMPCredential(SystemParams.CompanyID, iid);

            Response.Write("\"OK\"");
        }

        #endregion

        #region JDLink credential
        private void GetJDLinkTokenItems()
        {
            var user = GetCurrentLoginSession().User;
            JDAPICredentialProvider client = FleetServiceClientHelper.CreateClient<JDAPICredentialProvider>();
            AuthTokenItem[] items = client.GetJDLinkTokenItems(SystemParams.CompanyID);
            List<AuthTokenInfo> ls = new List<AuthTokenInfo>();
            if (items != null && items.Length > 0)
            {
                foreach (AuthTokenItem item in items)
                {
                    AuthTokenInfo ai = new AuthTokenInfo();
                    Helper.CloneProperty(ai, item);
                    ai.RequestTime = SystemParams.ConvertToUserTimeFromUtc(user, item.RequestTimeUtc);
                    ls.Add(ai);
                }
            }
            string json = JsonConvert.SerializeObject(ls);
            Response.Write(json);
            Response.End();
        }

        private void CreateJDLinkAuthUrl()
        {
            string absuri = Request.Url.AbsoluteUri;
            string url = absuri.Substring(0, absuri.LastIndexOf('/'));
            string redirecturl = url + "/Credentials.aspx?isjdlink=true";

            JDAPICredentialProvider client = FleetServiceClientHelper.CreateClient<JDAPICredentialProvider>();
            string result = client.CreateJDLinkAuthUrl(SystemParams.CompanyID, redirecturl);

            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }

        private void DeleteToken()
        {
            var iid = Request.Form["ClientData"];
            JDAPICredentialProvider client = FleetServiceClientHelper.CreateClient<JDAPICredentialProvider>();
            client.DeleteToken(SystemParams.CompanyID, iid, GetCurrentUser().IID, string.Empty);

            Response.Write("\"OK\"");
        }

        #endregion

        #region MyJohnDeere
        private void GetMyJDAPITokenItems()
        {
            var user = GetCurrentLoginSession().User;
            JDAPICredentialProvider client = FleetServiceClientHelper.CreateClient<JDAPICredentialProvider>();
            AuthTokenItem[] items = client.GetMyJDAPITokenItems(SystemParams.CompanyID);
            List<AuthTokenInfo> ls = new List<AuthTokenInfo>();
            if (items != null && items.Length > 0)
            {
                foreach (AuthTokenItem item in items)
                {
                    AuthTokenInfo ai = new AuthTokenInfo();
                    Helper.CloneProperty(ai, item);
                    ai.RequestTime = SystemParams.ConvertToUserTimeFromUtc(user, item.RequestTimeUtc);
                    ls.Add(ai);
                }
            }

            string json = JsonConvert.SerializeObject(ls);
            Response.Write(json);
            Response.End();
        }

        private void CreateMyJDAPIAuthUrl()
        {
            string absuri = Request.Url.AbsoluteUri;
            string url = absuri.Substring(0, absuri.LastIndexOf('/'));
            string redirecturl = url + "/Credentials.aspx?ismyjd=true";

            JDAPICredentialProvider client = FleetServiceClientHelper.CreateClient<JDAPICredentialProvider>();
            string result = client.CreateMyJDAPIAuthUrl(SystemParams.CompanyID, redirecturl);

            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }

        #endregion


        #region JDNotification credential

        private void GetNotificationSubscriptions()
        {
            var user = GetCurrentLoginSession().User;
            JDAPICredentialProvider client = FleetServiceClientHelper.CreateClient<JDAPICredentialProvider>();
            SubscriptionItem[] items = client.GetNotificationSubscriptions(SystemParams.CompanyID);
            List<SubscriptionInfo> ls = new List<SubscriptionInfo>();
            if (items != null && items.Length > 0)
            {
                foreach (SubscriptionItem item in items)
                {
                    SubscriptionInfo ai = new SubscriptionInfo();
                    Helper.CloneProperty(ai, item);
                    ai.CreateTime = SystemParams.ConvertToUserTimeFromUtc(user, item.CreateTimeUtc);
                    ls.Add(ai);
                }
            }
            string json = JsonConvert.SerializeObject(ls);
            Response.Write(json);
            Response.End();
        }

        private void CreateJDSubPubAuthUrl()
        {
            var name = Request.Form["ClientData"];
            string absuri = Request.Url.AbsoluteUri;
            string url = absuri.Substring(0, absuri.LastIndexOf('/'));
            string redirecturl = url + "/Credentials.aspx?isjdsub=true";

            JDAPICredentialProvider client = FleetServiceClientHelper.CreateClient<JDAPICredentialProvider>();
            string result = client.CreateJDSubPubAuthUrl(SystemParams.CompanyID, redirecturl, name);

            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }

        private void DeleteNotificationSubscription()
        {
            var iid = Request.Form["ClientData"];
            JDAPICredentialProvider client = FleetServiceClientHelper.CreateClient<JDAPICredentialProvider>();
            client.DeleteNotificationSubscription(SystemParams.CompanyID, iid);

            Response.Write("\"OK\"");
        }

        #endregion

        #region API Credential

        private void GetAPIDictionaries()
        {
            CredentialProvider crd = FleetServiceClientHelper.CreateClient<CredentialProvider>();
            APIDictionary[] items = crd.GetAPIDictionaries(SystemParams.CompanyID);
            items = items.Where(m => m.IsEnabled == true).ToArray();
            string json = JsonConvert.SerializeObject(items);
            Response.Write(json);
            Response.End();
        }

        private void GetAPICredentialDefs()
        {
            CredentialProvider crd = FleetServiceClientHelper.CreateClient<CredentialProvider>();
            APICredentialDef[] items = crd.GetAPICredentialDefs(SystemParams.CompanyID);
            string json = JsonConvert.SerializeObject(items);
            Response.Write(json);
            Response.End();
        }

        private void UpdateApiCredentialDefs()
        {
            var content = Request.Form["ClientData"];
            content = HttpUtility.HtmlDecode(content);
            var item = JsonConvert.DeserializeObject<APICredentialDef>(content);

            try
            {
                CredentialProvider crd = FleetServiceClientHelper.CreateClient<CredentialProvider>();
                crd.UpdateApiCredentialDefs(SystemParams.CompanyID, item, GetCurrentUser().IID);
            }
            catch (Exception ex)
            {
                Response.Write(JsonConvert.SerializeObject(ex.Message));
                return;
            }

            Response.Write("\"OK\"");
        }

        private void DeleteApiCredential()
        {
            var id = Request.Form["ClientData"];
            CredentialProvider crd = FleetServiceClientHelper.CreateClient<CredentialProvider>();
            crd.DeleteApiCredential(SystemParams.CompanyID, Convert.ToInt32(id), GetCurrentUser().IID);

            Response.Write("\"OK\"");
        }

        #endregion


        private void GetOrganizations()
        {
            var iid = Request.Form["ClientData"];
            JDAPICredentialProvider client = FleetServiceClientHelper.CreateClient<JDAPICredentialProvider>();
            JDOrganizationInfo[] items = client.GetOrganizations(SystemParams.CompanyID, iid);
            if (items == null)
                items = new JDOrganizationInfo[0];

            string json = JsonConvert.SerializeObject(items);
            Response.Write(json);
            Response.End();
        }

        private void GetJDOrganizationUrl()
        {
            var iid = Request.Form["ClientData"];
            JDAPICredentialProvider client = FleetServiceClientHelper.CreateClient<JDAPICredentialProvider>();
            string url = client.GetJDOrganizationUrl(SystemParams.CompanyID, iid);
            string json = JsonConvert.SerializeObject(url);
            Response.Write(json);
            Response.End();
        }


        /// <summary>
        /// 用于传输的临时Credential类
        /// </summary>
        public class CredentialObj
        {
            public string ID { get; set; }
            public string CredentialType { get; set; }
            public string Manufacture { get; set; }
            public string UrlKey { get; set; }
            public string UserName { get; set; }
            public string Password { get; set; }
            public bool Enabled { get; set; }
            public string OrgnizationID { get; set; }
            public string Notes { get; set; }
        }

        public class AEMPSourceItem
        {
            public string ManufactureID { get; set; }
            public string ManufactureName { get; set; }
            public string FleetUrl { get; set; }
            public string AutoServiceClass { get; set; }
        }

        public class JDCredentialObj
        {
            public string ID { get; set; }
            public string UserName { get; set; }
            public string ConsumerKey { get; set; }
            public string AuthorityUrl { get; set; }
            public DateTime ExpirationDateUtc { get; set; }
            public string ExpirationDateUtcStr { get { return ExpirationDateUtc == DateTime.MinValue ? "" : ExpirationDateUtc.ToShortDateString(); } }
        }
        public class JDNotifySubItem
        {
            public string ID { get; set; }
            public string UserName { get; set; }
            public string DisplayName { get; set; }
            public DateTime ExpireDate { get; set; }
            public string ExpireDateStr { get { return ExpireDate == DateTime.MinValue ? "" : ExpireDate.ToShortDateString(); } }
        }

        public class AuthTokenInfo : AuthTokenItem
        {
            public DateTime RequestTime { get; set; }
            public string RequestTimeStr { get { return RequestTime == DateTime.MinValue ? "" : RequestTime.ToString(); } }
        }

        public class SubscriptionInfo : SubscriptionItem
        {
            public DateTime CreateTime { get; set; }
            public string CreateTimeStr { get { return CreateTime == DateTime.MinValue ? "" : CreateTime.ToString(); } }
        }
    }
}
