using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IronIntel.Contractor.Machines;
using IronIntel.Contractor.Maintenance;
using System.Web;
using Foresight.ServiceModel;
using Foresight.Fleet.Services.AssetHealth;
using Foresight.Fleet.Services;

namespace IronIntel.Contractor.Site.Maintenance
{
    public class FuelRecordBasePage : ContractorBasePage
    {
        protected void ProcessRequest(string methodName)
        {
            object result = null;

            try
            {
                if (methodName != null)
                {
                    switch (methodName.ToUpper())
                    {
                        case "GETFUELRECORDS":
                            result = GetFuelRecords();
                            break;
                        case "GETFUELRECORDCHANGEHISTORY":
                            result = GetFuelRecordChangeHistory();
                            break;
                        case "SAVEFUELRECORD":
                            result = SaveFuelRecord();
                            break;
                        case "DELETEFUELRECORD":
                            result = DeleteFuelRecord();
                            break;
                        case "GETFUELTYPES":
                            result = GetFuelTypes();
                            break;
                        case "GETFUELRECORDCOMMENTS":
                            result = GetFuelRecordComments();
                            break;
                        case "ADDFUELRECORDCOMMENT":
                            result = AddFuelRecordComment();
                            break;
                        case "GETATTACHMENTS":
                            result = GetAttachments();
                            break;
                        case "ADDATTACHMENT":
                            result = AddAttachment();
                            break;
                        case "DELETEATTACHMENT":
                            result = DeleteAttachment();
                            break;
                    }
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "FuelRecordsBasePage" + methodName, ex.Message, ex.ToString());
            }
            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }


        private object GetFuelRecords()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var type = HttpUtility.HtmlDecode(clientdata[0]);
                    var sdatestr = HttpUtility.HtmlDecode(clientdata[1]);
                    var edatestr = HttpUtility.HtmlDecode(clientdata[2]);
                    var searchtxt = HttpUtility.HtmlDecode(clientdata[3]);
                    long assetid = 0;
                    long.TryParse(HttpUtility.HtmlDecode(clientdata[4]), out assetid);

                    DateTime beginDate = Helper.DBMinDateTime;
                    DateTime endDate = DateTime.MaxValue;
                    if (!DateTime.TryParse(sdatestr, out beginDate))
                        beginDate = Helper.DBMinDateTime;
                    if (!DateTime.TryParse(edatestr, out endDate))
                        endDate = DateTime.MaxValue;

                    FuelRecord[] fuels = CreateClient<FuelManagementClient>().GetFuelRecords(SystemParams.CompanyID, Convert.ToInt64(type), beginDate, endDate, searchtxt);
                    if (assetid > 0)
                        fuels = fuels.Where(m => m.AssetID == assetid).ToArray();

                    List<FuelRecordInfo> list = new List<FuelRecordInfo>();
                    foreach (FuelRecord fuel in fuels)
                    {
                        FuelRecordInfo fi = new FuelRecordInfo();
                        Helper.CloneProperty(fi, fuel);
                        fi.TransactionLocalDate = fuel.TransactionLocalDate;
                        list.Add(fi);
                    }

                    return list.ToArray();
                }
                else
                    return new FuelRecordInfo[0];

            }
            catch (Exception ex)
            {
                AddLog("ERROR", "FuelRecordBasePage.GetFuelRecords", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetFuelRecordChangeHistory()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Form["ClientData"];
                    long fuleid = Convert.ToInt64(HttpUtility.HtmlDecode(clientdata));

                    FuelRecordAuditInfo[] fuels = CreateClient<FuelManagementClient>().GetFuelRecordAuditItems(SystemParams.CompanyID, fuleid);

                    List<FuelRecordAuditItem> list = new List<FuelRecordAuditItem>();
                    foreach (FuelRecordAuditInfo fuel in fuels)
                    {
                        FuelRecordAuditItem fi = new FuelRecordAuditItem();
                        Helper.CloneProperty(fi, fuel);
                        //fi.TransactionDate = fi.TransactionDate.ToLocalTime(); 
                        fi.TransactionLocalDate = fuel.TransactionLocalDate;
                        list.Add(fi);
                    }

                    return list.ToArray();
                }
                else
                    return new FuelRecordInfo[0];

            }
            catch (Exception ex)
            {
                AddLog("ERROR", "FuelRecordBasePage.GetFuelRecords", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object SaveFuelRecord()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    FuelRecordInfo fuelrecord = JsonConvert.DeserializeObject<FuelRecordInfo>(clientdata);

                    FuelRecord record = new FuelRecord();
                    Helper.CloneProperty(record, fuelrecord);
                    long fuleid = record.FuelID;
                    if (record.FuelID == -1)
                    {
                        FuelRecord fr = CreateClient<FuelManagementClient>().AddNewFuelRecord(SystemParams.CompanyID, record, session.User.UID);
                        fuleid = fr.FuelID;
                    }
                    else
                    {
                        CreateClient<FuelManagementClient>().UpdateFuelRecord(SystemParams.CompanyID, record, session.User.UID);
                    }

                    return fuleid;
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeleteFuelRecord()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Form["ClientData"];
                    long fuleid = Convert.ToInt64(HttpUtility.HtmlDecode(clientdata));

                    CreateClient<FuelManagementClient>().DeleteFuelRecord(SystemParams.CompanyID, fuleid, session.User.UID);

                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetFuelTypes()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    List<KeyValuePair<string, string>> list = FuelManagementClient.FuelTypes.OrderBy(m => m.Value).ToList();
                    var type1 = list.FirstOrDefault(m => m.Value == "Unleaded Regular");
                    var type2 = list.FirstOrDefault(m => m.Value == "Unleaded Plus");
                    var type3 = list.FirstOrDefault(m => m.Value == "Diesel #1");
                    list.Remove(type1);
                    list.Remove(type2);
                    list.Remove(type3);
                    list = list.OrderBy(m => m.Value).ToList();
                    list.Insert(0, type1);
                    list.Insert(1, type2);
                    list.Insert(2, type3);
                    return list.ToArray();
                }
                else
                    return new StringKeyValue[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "FuelRecordBasePage.GetFuelTypes", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetFuelRecordComments()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string fuleid = Request.Form["ClientData"];

                    CommentInfo[] comments = CreateClient<DocCommentProvider>().GetComments(SystemParams.CompanyID, "FuelRecord", fuleid);
                    List<CommentItem> list = new List<CommentItem>();
                    foreach (var c in comments)
                    {
                        CommentItem citem = new CommentItem();
                        Helper.CloneProperty(citem, c);

                        list.Add(citem);
                    }

                    return list.ToArray();
                }
                else
                {
                    return new CommentItem[0];
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object AddFuelRecordComment()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    string fuleid = ps[0];
                    string comment = ps[1];

                    CreateClient<DocCommentProvider>().SubmitComment(SystemParams.CompanyID, user.IID, "FuelRecord", fuleid.ToString(), comment, false);
                }
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #region Attachment

        private object GetAttachments()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string fuleid = HttpUtility.HtmlDecode(Request.Form["ClientData"]);

                    AttachmentItem[] atts = CreateClient<AttachmentProvider>().GetAttachmentItems(SystemParams.CompanyID, "FuelRecord", fuleid);
                    if (atts == null || atts.Length <= 0)
                        return new AttachmentItemClient[0];

                    List<AttachmentItemClient> list = new List<AttachmentItemClient>();
                    foreach (Foresight.Fleet.Services.AttachmentItem att in atts)
                    {
                        AttachmentItemClient item = new AttachmentItemClient();
                        Helper.CloneProperty(item, att);
                        list.Add(item);
                    }
                    return list.OrderBy(m => m.AddedOn).ToArray();
                }
                else
                    return new AttachmentItemClient[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object AddAttachment()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string fuleid = HttpUtility.HtmlDecode(Request.Form["ClientData"]);

                    HttpPostedFile uploadFile = null;
                    byte[] iconfilebyte = null;
                    if (Request.Files.Count > 0)
                    {
                        uploadFile = Request.Files[0];
                        iconfilebyte = ConvertFile2bytes(uploadFile);
                    }

                    string FileName = uploadFile == null ? "" : uploadFile.FileName;
                    long attid = CreateClient<AttachmentProvider>().AddAttachment(SystemParams.CompanyID, "FuelRecord", fuleid, FileName, "", iconfilebyte);

                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeleteAttachment()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string attachid = HttpUtility.HtmlDecode(Request.Form["ClientData"]);

                    CreateClient<AttachmentProvider>().DeleteAttachment(SystemParams.CompanyID, long.Parse(attachid));
                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion

    }
    public class AttachmentItemClient : AttachmentItem
    {
        public string AddedOnStr { get { return AddedOn.ToString(); } }
        public byte[] FileData { get; set; }
    }
}
