using LHDN.CRM.BC.Common;
using LHDN.CRM.BC.Services;
using LHDN.CRM.Models.ViewModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;

namespace LHDN.CRM.WebAPI.Controllers
{
    public class BaseApiController : ApiController
    {
        AuditService svcAudit = new AuditService();
        ErrorService svcError = new ErrorService();
        TaskService svcTask = new TaskService();
        GeneralService svcAlertNotify = new GeneralService();

        #region Audit Log

        public virtual void AuditLogTxn(AuditService.AuditEventID auditEventID,
            AuditService.ResultType resultType,
            AuditService.ActionType actionType,
            string userID,
            DateTime createdDate,
            string additionalInfo)
        {
            AuditLogTxn(auditEventID,
                resultType,
                actionType,
                userID,
                createdDate,
                additionalInfo,null,null);
        }

        public virtual void AuditLogTxn(AuditService.AuditEventID auditEventID,
            AuditService.ResultType resultType,
            AuditService.ActionType actionType,
            string userID,
            DateTime createdDate,
            string additionalInfo,
            params AuditDetailViewModel[] auditEvents)
        {
            AuditLogTxn(auditEventID,
                resultType,
                actionType,
                userID,
                createdDate,
                additionalInfo,
                auditEvents.ToList());
        }

        public virtual void AuditLogTxn(AuditService.AuditEventID auditEventID,
            AuditService.ResultType resultType,
            AuditService.ActionType actionType,
            string userID,
            DateTime createdDate,
            string additionalInfo = null,
            List<AuditDetailViewModel> lstAuditDetails = null,
            string refTableName = null,
            long? refTableID = null)
        {
            string creator = HttpContext.Current.User.Identity.Name=="" ? "SYSTEM" : HttpContext.Current.User.Identity.Name;
            svcAudit.SaveAudit((int)auditEventID, 
                resultType,
                actionType,
                userID == "" ? "SYSTEM" : userID,
                creator,
                createdDate,
                additionalInfo,
                lstAuditDetails,
                refTableName,
                refTableID);
        }

        #endregion

        #region Error Log

        public virtual void LogError(string message, string userId)
        {
            svcError.LogError(message, userId);
        }

        #endregion

        public virtual string ModelStateErrMessage(ModelStateDictionary obj)
        {
            return string.Join(Environment.NewLine,
                    obj.Values.Where(E => E.Errors.Count > 0)
                    .SelectMany(E => E.Errors)
                    .Select(E => E.ErrorMessage).Distinct()
                    .ToArray());
        }

        public virtual void RecentActivityTxn(string strModule,
                                              long lngRefID,
                                              string strDescription, 
                                              string strCreatedBy,
                                              string strCreatedByName,
                                              DateTime dtCreatedDateTime,
                                              string strURL)
        {
            svcTask.InsertRecentActivity(strModule, lngRefID, strDescription, strCreatedBy, strCreatedByName, dtCreatedDateTime, strURL);
        }

        public virtual void RecentTaskAlertNotify(string strCurrentLoginId,
                                              Int16 intTableTypeId,
                                               long lngRefID,
                                               int intMessageTypeID,
                                               string strDescription,
                                               string strURL,
                                               bool blnIsRead,
                                               string strCreatedBy,
                                               string strCreatedByName,
                                               DateTime dtCreatedDateTime)
        {
            svcAlertNotify.InsertTaskAlertNotify(strCurrentLoginId, intTableTypeId, lngRefID, intMessageTypeID, strDescription, strURL, blnIsRead, strCreatedBy, strCreatedByName, dtCreatedDateTime);
        }

        //public void UpdateCache(UserCacheViewModel objCache)
        //{
        //    string URL = Utilities.GetAppSetting("LHDN.CRM.UpdateCacheWebAPI");
        //    if (!string.IsNullOrEmpty(URL))
        //    {
        //        string DATA = JsonConvert.SerializeObject(objCache);

        //        HttpClient client = new HttpClient();
        //        client.BaseAddress = new Uri(URL);
        //        CredentialCache cc = new CredentialCache();
        //        cc.Add(
        //            new Uri(URL),
        //            "NTLM",
        //            new NetworkCredential("user", "password", "domain"));
        //        //Generate Api Key
        //        string strReqtimestamp = DateTime.Now.ToString();
        //        string secretKey = string.Empty;
        //        string sH = string.Empty;
        //        secretKey = Utilities.GetAppSetting("CRMWebApi.SecretKey") + strReqtimestamp;
        //        sH = SHA1(secretKey);

        //        //Api Key
        //        client.DefaultRequestHeaders.Add("_apikey", sH);
        //        client.DefaultRequestHeaders.Add("_reqtimestamp", strReqtimestamp);

        //        // Add an Accept header for JSON format.
        //        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        //        System.Net.Http.HttpContent content = new StringContent(DATA, UTF8Encoding.UTF8, "application/json");
        //        HttpResponseMessage messge = client.PostAsync(URL, content).Result;
        //        string description = string.Empty;
        //        if (messge.IsSuccessStatusCode)
        //        {
        //            string result = messge.Content.ReadAsStringAsync().Result;
        //            description = result;
        //        }

        //        //Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; 
        //        //for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.

        //        client.Dispose();
        //    }
        //}

        private string SHA1(string sIn)
        {
            System.Security.Cryptography.SHA1CryptoServiceProvider sha1Obj = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            Byte[] bytesToHash = System.Text.Encoding.ASCII.GetBytes(sIn);
            string strResult = string.Empty;
            bytesToHash = sha1Obj.ComputeHash(bytesToHash);

            foreach (byte b in bytesToHash)
            {
                strResult += b.ToString("x2");
            }
            return strResult;
        }
    }
}