using Foresight.Fleet.Services.Asset;
using Foresight.Fleet.Services.Customer;
using Foresight.ServiceModel;
using IronIntel.Contractor;
using IronIntel.Contractor.Machines;
using IronIntel.Contractor.MapView;
using IronIntel.Contractor.Site;
using IronIntel.Contractor.Users;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MapViewChart : ContractorBasePage
{
    public string LocationHistoryDateFrom = DateTime.Now.Date.AddMonths(-2).ToShortDateString();
    public string LocationHistoryDateTo = DateTime.Now.Date.ToShortDateString();

    private string Logo1html = "<img class=\"logo\" src=\"{0}\" style=\"width:24px;height:24px; \" />";
    protected string Logo1 = "";

    protected string MachineID = "";
    protected string VIN = "";
    protected string Datasource = "";
    protected string CompanyID = "";
    public string CurrentDate = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        string tp = Request.Params["tp"];
        if (string.Compare(tp, "ashx", true) == 0)
        {
            ProcessRequest();
        }
        else if (!IsPostBack)
        {
            Title = PageTitle;
            if (CheckLoginSession())
            {
                var cmp = SystemParams.GetCompanyInfo();
                GetLogoHtml(cmp);
            }

            MachineID = Request.Params["machineid"] ?? "";
            VIN = Request.Params["vin"] ?? "";
            Datasource = Request.Params["ds"] ?? "";
            CompanyID = GetCompanyID(MachineID, VIN);
        }
        DateTime userlocaldate = SystemParams.ConvertToUserTimeFromUtc(GetCurrentLoginSession().User, DateTime.UtcNow);
        CurrentDate = userlocaldate.ToShortDateString();
    }

    private void GetLogoHtml(CustomerInfo cmp)
    {
        var root = ResolveUrl("~/");

        var sessionid = GetLoginSessionID(Request);
        StringKeyValue kv = UserManagement.GetSiteHederStyleLogo(sessionid);
        string styleid = "-1";
        bool hasDealerLogo = false;
        if (kv != null)
        {
            styleid = kv.Key;
            hasDealerLogo = Helper.IsTrue(kv.Tag2);
        }

        if (cmp.IsContractor)
        {//Logo1 Dealer;
            CustomerInfo dealer = SystemParams.GetFirstDealerInfo();
            if (dealer != null)
            {
                if (hasDealerLogo)//user Dealer
                {
                    Logo1 = string.Format(Logo1html, root + "titlelogo.ashx?tp=dealer&cmpid=" + dealer.ID + "&styid=" + styleid);
                }
                else if (SystemParams.HasLOGO(dealer.ID))//Dealer
                {
                    Logo1 = string.Format(Logo1html, root + "titlelogo.ashx?tp=dealer&cmpid=" + dealer.ID);
                }
                else
                {
                    Logo1 = string.Format("<div class=\"logo\">{0}</div>", dealer.Name);
                }
            }
            else
            {
                Logo1 = string.Empty;
            }
        }
        else
        {
            if (hasDealerLogo)//user Dealer
            {
                Logo1 = string.Format(Logo1html, root + "titlelogo.ashx?tp=dealer&cmpid=" + cmp.ID + "&styid=" + styleid);
            }
            else if (SystemParams.HasLOGO(cmp.ID))//Dealer
            {
                Logo1 = string.Format(Logo1html, root + "titlelogo.ashx?tp=dealer&cmpid=" + cmp.ID);
            }
            else
            {
                Logo1 = string.Format("<div class=\"logo\">{0}</div>", cmp.Name);
            }
        }
    }

    protected void ProcessRequest()
    {
        object result = null;

        string methodName = Request.Form["MethodName"];
        try
        {
            if (methodName != null)
            {
                switch (methodName.ToUpper())
                {
                    case "GETMACHINEITEM":
                        result = GetMachineItem();
                        break;
                }
            }
        }
        catch (System.Threading.ThreadAbortException)
        {
            throw;
        }
        catch (Exception ex)
        {
            var clientdata = Request.Form["ClientData"];
            SystemParams.WriteLog("error", "MapViewChart." + methodName + ":" + clientdata, ex.Message, ex.ToString());
        }
        string json = JsonConvert.SerializeObject(result);
        Response.Write(json);
        Response.End();
    }

    private object GetMachineItem()
    {
        var session = GetCurrentLoginSession();
        if (session == null)
            return null;
        var clientdata = Request.Form["ClientData"];
        string[] MachinIDOrVIN = JsonConvert.DeserializeObject<string[]>(clientdata);
        if (MachinIDOrVIN != null && MachinIDOrVIN.Length == 3)
        {
            string machineids = MachinIDOrVIN[0];
            string vins = MachinIDOrVIN[1];
            string datasource = MachinIDOrVIN[2];
            if (string.IsNullOrEmpty(machineids) && string.IsNullOrEmpty(vins))
                return null;

            string machineid = machineids.Split(',')[0];
            string vin = vins.Split(',')[0];

            string companyid = "";
            if (SystemParams.IsDealer)
            {
                var client = FleetServiceClientHelper.CreateClient<AssetQueryClient>(session.SessionID);
                AssetBasicInfo m = null;
                if (string.IsNullOrEmpty(machineid))
                {
                    m = client.FromAdminAssetBasicInfoByVin(vin);
                    machineid = m.ID.ToString();
                }
                else
                    m = client.FromAdminAssetBasicInfoById(long.Parse(machineid));
                if (m != null)
                    companyid = m.ContractorID;

                if (string.IsNullOrEmpty(companyid))
                    companyid = SystemParams.CompanyID;
            }
            else if (string.IsNullOrEmpty(machineid))
            {
                machineid = MachineManagement.GetMachineIDByVIN(vin);
            }
            if (string.IsNullOrEmpty(companyid))
                companyid = SystemParams.CompanyID;
            
            long mid = 0;
            if (!long.TryParse(machineid, out mid))
                return null;
            var md = AssetMapViewManagement.GetAssetDetailItem(session.SessionID, companyid, mid, datasource);
            return md;
        }
        return null;
    }
    public bool IsDealer
    {
        get
        {
            return SystemParams.IsDealer;
        }
    }

    private string GetCompanyID(string machineid, string vin)
    {
        var session = GetCurrentLoginSession();
        if (session == null)
            return null;
        string companyid = "";
        if (SystemParams.IsDealer)
        {
            var client = FleetServiceClientHelper.CreateClient<AssetQueryClient>(session.SessionID);
            AssetBasicInfo m = null;
            if (string.IsNullOrEmpty(machineid))
            {
                m = client.FromAdminAssetBasicInfoByVin(vin);
                machineid = m.ID.ToString();
            }
            else
            {
                long mid = 0;
                if (long.TryParse(machineid, out mid))
                    m = client.FromAdminAssetBasicInfoById(mid);
            }
            if (m != null)
                companyid = m.ContractorID;

            if (string.IsNullOrEmpty(companyid))
                companyid = SystemParams.CompanyID;
        }

        return companyid;
    }
}