using AddressValidation.DataLayer.Entities;
using DataMatch.AddressVerification;
using DataMatch.AddressVerification.Contracts;
using DataMatch.AddressVerification.Entities;
using DevExpress.Web;
using log4net;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AddressValidationWebSample
{
    public partial class Default : System.Web.UI.Page
    {
        private readonly ILog Log = LogManager.GetLogger(nameof(Default));

        private const String ZipDefaultValue = "00000";

        [System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod]
        public static List<String> SearchAddresses(string prefixText, int count)
        {
            var cassManager = CassManagerFactory.Create(DataMatch.AddressVerification.Enums.CassManagerTypes.Custom);
            ICassRequest cassRequest = new CassRequest { Query = prefixText };
            var cassResponses = cassManager.GetAddressSuggestions(cassRequest).Responses;

            List<String> addressList = new List<string>();
            foreach (var response in cassResponses)
            {
                var html = $"{response.AddressPrimary}|{response.AddressSecondary}|{response.City}|{response.State}";
                var item = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(response.AddressMain, html);
                addressList.Add(item);
            }

            return addressList;
        }

        private void BindData()
        {
            holdingGrid.DataSource = MatchingWorker.Instance.HoldingTable;
            suppressedGrid.DataSource = MatchingWorker.Instance.SuppressedTable;
            masterGrid.DataSource = MatchingWorker.Instance.MasterTable;
            lblProgress.Text = MatchingWorker.Instance.ProcessesCompleted;

            holdingGrid.DataBind();
            suppressedGrid.DataBind();
            masterGrid.DataBind();

            holdingGrid.PageIndex = holdingGrid.PageCount - 1;
            suppressedGrid.PageIndex = suppressedGrid.PageCount - 1;
            masterGrid.PageIndex = masterGrid.PageCount - 1;
        }

        private void ResetSubmitForm()
        {
            firstNameTxt.Text = String.Empty;
            lastNameTxt.Text = String.Empty;
            addressTxt.Text = String.Empty;
            address2Txt.Text = String.Empty;
            cityTxt.Text = String.Empty;
            stateTxt.Text = String.Empty;
            zipTxt.Text = ZipDefaultValue;
            phoneTxt.Text = String.Empty;
            emailTxt.Text = String.Empty;
        }

        protected void Page_Load(Object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            BindData();
        }

        protected void insertBtn_Click(Object sender, EventArgs e)
        {
            ContactInfo contactInfo = new ContactInfo
            {
                FirstName = firstNameTxt.Text,
                LastName = lastNameTxt.Text,
                Address1 = addressTxt.Text,
                Address2 = address2Txt.Text,
                City = cityTxt.Text,
                State = stateTxt.Text,
                Zip = zipTxt.Text,
                Phone = phoneTxt.Text,
                Email = emailTxt.Text
            };

            MatchingWorker.Instance.AnalyzeRecord(contactInfo);

            BindData();
            ResetSubmitForm();
        }

        protected void btnOpenPopUp_Click(Object sender, EventArgs e)
        {
            ModalPopupExtender.Show();
        }

        protected void btnCancel_Click(Object sender, EventArgs e)
        {
            ModalPopupExtender.Hide();
            ResetSubmitForm();
        }

        protected void statusTimer_Tick(Object sender, EventArgs e)
        {
        }

        protected void btnReset_Click(Object sender, EventArgs e)
        {
        }

        protected void suppressedGrid_HtmlRowPrepared(Object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
        {
            if (MatchingWorker.Instance.IsLastInsertedRecordUnique.HasValue 
                && !MatchingWorker.Instance.IsLastInsertedRecordUnique.Value 
                && e.VisibleIndex == (sender as ASPxGridView).VisibleRowCount - 1 )
            {
                e.Row.BackColor = System.Drawing.Color.Yellow;
            }
        }

        protected void masterGrid_HtmlRowPrepared(Object sender, ASPxGridViewTableRowEventArgs e)
        {
            if (MatchingWorker.Instance.IsLastInsertedRecordUnique.HasValue
                && MatchingWorker.Instance.IsLastInsertedRecordUnique.Value
                && e.VisibleIndex == (sender as ASPxGridView).VisibleRowCount - 1)
            {
                e.Row.BackColor = System.Drawing.Color.Yellow;
            }
        }
    }
}