using System;

using System.Collections;
using System.ComponentModel;
using System.Configuration;

using System.Data;
using System.Drawing;
using System.Web;

using System.Web.SessionState;
using System.Web.UI;

using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using System.Xml;
using System.Xml.Xsl;

using Cara.BusinessObjects;
using Cara.BaseClasses;
using Cara.Utils.DAL;

using Cara.YourCarMotorInsuranceWebservice;

using NHibernate;
using NHibernate.Expression;

namespace Example.ajax
{
    /// <summary>
    /// Summary description for insuranceproxy.
    /// </summary>

    public class insuranceproxy 
    {

        private Hashtable    cookieValues    = new Hashtable();

        public insuranceproxy() 
        {

        }

        public override void Page_Load (object sender, System.EventArgs e)  
        {

        Response.ContentType    = "text/plain";
            string    sReturn            = string.Empty;

            string    sMethod            = Request.QueryString["method"];
            
            if(sMethod.Equals("group_quotations"))

            {
                sReturn        = groupQuotations();
            }
            else if(sMethod.Equals("full_quotations"))

            {
                sReturn        = fullQuotations();
            }

            Response.Write(sReturn);

        }


        private string groupQuotations()
        {

            string    sReturn        = string.Empty;

            XmlDocument tempDoc = new XmlDocument();

            XmlWriter xmlWriter = new XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8);

        
            try
            {
                YourCarMotorInsuranceWebservice.InsuranceCalculation        s = new YourCarMotorInsuranceWebservice.InsuranceCalculation();

                YourCarMotorInsuranceWebservice.InsuranceCalculationData    d = new YourCarMotorInsuranceWebservice.InsuranceCalculationData();
                d.DateOfBirth        = Request.Form["dob"];

                d.Gender            = bool.Parse(Request.Form["gender"]);

                d.HasAccident        = bool.Parse(Request.Form["accidents"]);

                d.HasConviction        = bool.Parse(Request.Form["convictions"]);

                d.IsGaraged            = bool.Parse(Request.Form["garaged"]);

                d.Mileage            = Convert.ToInt32(Request.Form["insurancemileage"]);

                d.PostCode            = Request.Form["postcode"];
                d.PromoCode            = Request.Form["promocode"];

                d.RestrictionsId    = Convert.ToInt32(Request.Form["covertype"]);

                string[] sIGroups    = Request.Form["insurancegroups"].Split(',');

                ArrayList arrWebServiceGroups    = new ArrayList();
                ArrayList arrCachedGroups        = new ArrayList();

                
                for( int i = 0; i < sIGroups.Length; i++ ) 
                {

                    if(Session["insuranceGroup" + sIGroups[i]] == null && !sIGroups[i].Equals("-1")) 
                    {

                        arrWebServiceGroups.Add( Convert.ToInt32( sIGroups[i] ) );

                    } 
                    else if(!sIGroups[i].Equals("-1"))

                    {
                        arrCachedGroups.Add( Convert.ToInt32( sIGroups[i] ) );

                    }
                }

                XmlNode result = null;
                if( arrWebServiceGroups.Count > 0 ) 
                {

                    result = tempDoc.ImportNode( s.CalculateListFromGroups(XXXXXXXXXXX, XXXXXXXXXXX, 1, d, (int[])arrWebServiceGroups.ToArray( typeof( int )) ), true );

                } 
                else 
                {
                    
                    tempDoc.LoadXml("<InsuranceCalculationResult><Calculations></Calculations></InsuranceCalculationResult>");

                    result = (XmlNode)tempDoc.DocumentElement;
                }
                
                if(result.InnerXml.IndexOf("Exception") > -1)

                {
                    throw new Exception("error");
                }

                else
                {
                    // cache xml nodes for each insurance group calculation
                    XmlNodeList fragment = result.SelectNodes("//Calculation");

                    foreach( XmlNode x in fragment ) 
                    {
                        int iInsuranceGroup = Convert.ToInt32(x.SelectSingleNode("Vehicle/InsuranceGroup").InnerText);

                        Session["insuranceGroup" + iInsuranceGroup] = x;

                    }

                    // append cached results
                    XmlNode x_CalculationsNode = result.SelectSingleNode("./Calculations");

                    foreach( int i in arrCachedGroups ) 
                    {
                        x_CalculationsNode.AppendChild( tempDoc.ImportNode( (XmlNode)Session["insuranceGroup" + i], true ) );

                    }

                    // transform into javascript calls
                    XslTransform xslTransformGroupListing = new XslTransform();

                    xslTransformGroupListing.Load(Server.MapPath(@"..\xml\InsuranceGroupListing.xsl"));

                    xslTransformGroupListing.Transform(result, null, xmlWriter, null);

                }
            } 
            catch (Exception ex)
            {
                LogError(ex.Message, ex);

                Response.StatusCode        = 500;
            } 
            finally 
            {
                xmlWriter.Flush();

                xmlWriter.Close();
            }

            return sReturn;

        }


        private string fullQuotations()
        {

            string    sReturn        = string.Empty;
            XmlDocument tempDoc = new XmlDocument();

            XmlWriter xmlWriter = new XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8);

        
            try
            {
                YourCarMotorInsuranceWebservice.InsuranceCalculation        s = new LloydLatchfordWebService.InsuranceCalculation();

                YourCarMotorInsuranceWebservice.InsuranceCalculationData    d = new LloydLatchfordWebService.InsuranceCalculationData();
                d.DateOfBirth        = Request.Form["dob"];

                d.Gender            = bool.Parse(Request.Form["gender"]);

                d.HasAccident        = bool.Parse(Request.Form["accidents"]);

                d.HasConviction        = bool.Parse(Request.Form["convictions"]);

                d.IsGaraged            = bool.Parse(Request.Form["garaged"]);

                d.Mileage            = Convert.ToInt32(Request.Form["insuranceMileage"]);

                d.PostCode            = Request.Form["postcode"];
                d.PromoCode            = Request.Form["promocode"];

                d.RestrictionsId    = Convert.ToInt32(Request.Form["covertype"]);

                LloydLatchfordWebService.InsuranceCalculationVehicle    veh        = new LloydLatchfordWebService.InsuranceCalculationVehicle();
                veh.CapId                                = Convert.ToInt32(Request.Form["capid"]);

                XmlNode        result                        = null;
                result                                    = s.Calculate(XXXXXXXXXXXX, XXXXXXXXXXXX, 1, d, veh);

                if(result.SelectSingleNode("Exceptions") == null)

                {
                    GetCookie();

                    if(cookieValues.Count > 0)

                    {
                        // get the vehicle's capid
                        Vehicle                v                    = (Vehicle)Db.Session.CreateCriteria(typeof(Vehicle))

                            .Add(Expression.Eq("CapId", Convert.ToInt32(Request.Form["capid"])))

                            .Add(Expression.Eq("Datasetid", m_Site.Preferences.Datasetid))

                            .UniqueResult();
                        XsltArgumentList    args                = new XsltArgumentList();

                        args.AddParam("vehiclePrice", "", v.OtrPrice);

                        args.AddParam("dob", "", cookieValues["dob"]);

                        args.AddParam("coverType", "", cookieValues["covertype"]);

                        args.AddParam("capId", "", v.CapId);

                        args.AddParam("email", "", cookieValues["email"]);

                        args.AddParam("forename", "", cookieValues["forename"]);

                        args.AddParam("garage", "", cookieValues["garaged"]);

                        args.AddParam("gender", "", cookieValues["gender"]);

                        args.AddParam("postcode", "", cookieValues["postcode"]);

                        args.AddParam("surname", "", cookieValues["surname"]);

                        args.AddParam("tracker", "", cookieValues["tracker"]);

                        args.AddParam("mileage", "", cookieValues["insurancemileage"]);

                        args.AddParam("claim", "", cookieValues["accidents"]);

                        args.AddParam("conviction", "", cookieValues["convictions"]);

                        args.AddParam("siteId", "", 1);

                        args.AddParam("telephone", "", cookieValues["telephone"]);

                        args.AddParam("building", "", cookieValues["building"]);

                        args.AddParam("buildingName", "", cookieValues["buildingname"]);

                        args.AddParam("title", "", cookieValues["title"]);

                        args.AddParam("imagePath", "", m_Site.ImagePath);

                        args.AddParam("isNew", "", "true");

                        args.AddParam("vehicleAge", "", DateTime.Now.Year);

                        args.AddParam("webserviceUserId", "", "3410");

                        XslTransform        xslTransform        = new XslTransform();
                        xslTransform.Load(Server.MapPath(@"..\whitelabel\" + m_Site.Id + @"\includes\insurance_template.xsl"));

                        xslTransform.Transform(result, args, xmlWriter, null);

                    }
                    else
                    {
                        sReturn        = "<div id=\"insuranceUnavailableMessage\">Unfortuantely we were unable to calculate quote due to the credentials supplied.<div style=\"display: none;\">Cookie Details</div></div>";

                    }
                }
                else
                {
                    sReturn        = "<div id=\"insuranceUnavailableMessage\">Unfortuantely we were unable to calculate quote due to the credentials supplied.<div style=\"display: none;\">Exception In XML</div></div>";

                }
            } 
            catch (Exception ex)
            {
                LogError(ex.Message, ex);

                Response.StatusCode        = 501;
                sReturn        = "<div id=\"insuranceUnavailableMessage\">Unfortuantely we were unable to calculate quote due to the credentials supplied.<div style=\"display: none;\">Error Thrown</div></div>";

            } 
            finally 
            {
                xmlWriter.Flush();
                xmlWriter.Close();

            }

            return sReturn;
        }

        private void GetCookie()

        {
            HttpCookie    cookie    = Request.Cookies["insuranceQuoteFormDetails"];

            string[]    sSplit    = Server.UrlDecode(cookie.Value).Split(',');

            foreach(string s in sSplit)
            {
                string[] sValue    = s.Split('=');

                cookieValues.Add(sValue[0], sValue[1]);

            }
        }
    }
}