/// <summary>
        /// Creates a Xero line item for every Aquairum line item with a matching Invoice number,  and bundles them up into a Xero invoice
        /// </summary>
        /// <param name="theInvoiceLineItemToConvert"></param>
        /// <returns></returns>
        public static XeroApi.Model.Invoice ConvertMultipleOutboundInvoiceLineItemsToXeroInvoice(OutboundInvoiceLineItemList theInvoiceLineItemsToConvert, OutboundInvoiceLineItem theLineItemToMatchTo, Datalayer.Xero.Interresolve.InterResolveXeroService aService)
        {
            try
            {
                XeroApi.Model.Invoice theInvoiceToReturn = new XeroApi.Model.Invoice();
                theInvoiceToReturn.LineItems = new XeroApi.Model.LineItems();
                theInvoiceToReturn.Contact = new XeroApi.Model.Contact(); //NEED TO SPECIFY A CONTACT

                //assign the xero contact
                aService.LoginToXero();
                theInvoiceToReturn.Contact = aService.GetXeroContactFromAquariumInvoiceLineItemList(theLineItemToMatchTo);

                //assign top level invoice fields for the passed invoice to the Xero counterpart
                theInvoiceToReturn.InvoiceNumber = theLineItemToMatchTo.InvoiceNumber.ToString();
                theInvoiceToReturn.Status = "DRAFT";
                theInvoiceToReturn.Type = "ACCREC"; //Sales invoice
                theInvoiceToReturn.Reference = theLineItemToMatchTo.SageNarrative + " " + theLineItemToMatchTo.YourRef;
                theInvoiceToReturn.LineAmountTypes = XeroApi.Model.LineAmountType.Exclusive;
                theInvoiceToReturn.SubTotal = theLineItemToMatchTo.OriginalPurchaseInvoiceTotal;
                theInvoiceToReturn.DueDate = DateTime.Now.AddDays(14);
                theInvoiceToReturn.Date = theLineItemToMatchTo.InvoiceDate;
               // theInvoiceToReturn.TotalTax //this must be calculated AFTER by summing all the line item VATs
                theInvoiceToReturn.Total = theLineItemToMatchTo.OriginalPurchaseInvoiceTotal;

                //iterate through and if number matches specified invoice number, add it to the list
                decimal RunningVATTotalForInvoice = new decimal(0.00);

                for (int i = 0; i < theInvoiceLineItemsToConvert.OutboundInvoiceLineItems.Count(); i++)
                {
                    if (theInvoiceLineItemsToConvert.OutboundInvoiceLineItems.ElementAt(i).InvoiceNumber == theLineItemToMatchTo.InvoiceNumber)
                    {
                         //if the invoice numbers match, create a new line item and add this line item to the list
                        XeroApi.Model.LineItem aLineItem = new XeroApi.Model.LineItem();
                        aLineItem.Quantity = 1; //always one line item
                        aLineItem.Description = theInvoiceLineItemsToConvert.OutboundInvoiceLineItems.ElementAt(i).InvoiceType; //
                        aLineItem.UnitAmount = theInvoiceLineItemsToConvert.OutboundInvoiceLineItems.ElementAt(i).OriginalPurchaseInvoiceAmount;
                        aLineItem.TaxAmount = theInvoiceLineItemsToConvert.OutboundInvoiceLineItems.ElementAt(i).OriginalPurchaseInvoiceVAT;
                        aLineItem.LineAmount = (aLineItem.Quantity * aLineItem.UnitAmount);
                        aLineItem.AccountCode = InterResolveXeroService.GetXeroAccountCodeForAquariumLineItem(theInvoiceLineItemsToConvert.OutboundInvoiceLineItems.ElementAt(i));

                        //add the VAT to the running total
                        RunningVATTotalForInvoice =+ theInvoiceLineItemsToConvert.OutboundInvoiceLineItems.ElementAt(i).OriginalPurchaseInvoiceVAT;

                        //add it to the list
                        theInvoiceToReturn.LineItems.Add(aLineItem);
                     }

                 }

                //assign the overall invoice VAT
                theInvoiceToReturn.TotalTax = RunningVATTotalForInvoice;

                return theInvoiceToReturn;
                }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        static void Main(string[] args)
        {
            AquariumLogin login = new AquariumLogin();
            login.LoginToAquarium();

            LoggedOnUserResult theUserResult = login.GetLoggedOnUserResult();

            Datalayer.Xero.Interresolve.AquariumUserManagement.SessionDetails sessionDetails = new Datalayer.Xero.Interresolve.AquariumUserManagement.SessionDetails(); //set this from the logon

            //set the USER sesson
            sessionDetails.SessionKey = theUserResult.SessionKey;
            sessionDetails.Username = theUserResult.Username;
            sessionDetails.ThirdPartySystemId = 29;

            //map a custom session
            Datalayer.Xero.Interresolve.AquariumCustomProcessing.SessionDetails customSessionDetails = new Datalayer.Xero.Interresolve.AquariumCustomProcessing.SessionDetails();
            customSessionDetails.SessionKey = sessionDetails.SessionKey;
            customSessionDetails.ThirdPartySystemId = 29;
            customSessionDetails.Username = theUserResult.Username;

            //set the session details here
            CustomProcessingSoapClient customSdk = new CustomProcessingSoapClient();

            //now call the 'QueryInvoices Method
            OutboundInvoiceLineItemList theOutboundInvoices = new OutboundInvoiceLineItemList();

            //gets all invoices
            theOutboundInvoices.Get();

            //do something with them

            List<DataTable> InvoiceOptions = OutboundInvoiceLineItemList.GetInvoiceOptions();
            /*
            //string InvoiceType = "Sales Invoice";

            //map to xml

            var InvoicesThisMonth = (from invoice in theResults.AsEnumerable()
                                     .Where(x => x.Field<string>("WhenCreated").ToString().Substring(3, 5) == DateTime.Now.ToString("dd/MM/yy").Substring(3, 5)) //this month
                                     .Where(x => x.Field<string>("Invoice Type").ToString() = InvoiceType) //sales invoices
                                     .Where(x => x.Field<string>("Imported Into Sage").ToString().ToLower() == "false") //not been imported
                                     .Where( (x => x.Field<string>("Imported Into Sage").ToString() == "Claimant's InterResolve Scheme Fee"))
                                     select invoice
                                     );
            //post
               */
        }
        public ActionResult ImportInvoice()
        {
            //create the correct company

            //get the Invoices to import from the session
            ObservableCollection<Datalayer.Xero.Interresolve.OutboundInvoiceLineItem> theAquariumInvoicesToImportFromSession = (ObservableCollection<Datalayer.Xero.Interresolve.OutboundInvoiceLineItem>)Session["InvoicesToImport"];

            OutboundInvoiceLineItemList theAquariumInvoicesToImport = new OutboundInvoiceLineItemList();
            theAquariumInvoicesToImport.OutboundInvoiceLineItems = theAquariumInvoicesToImportFromSession.ToList();

            //convert from Aquarium invoices to Xero Invoices
            XeroApi.Model.Invoices theXeroInvoicesToImport = new XeroApi.Model.Invoices(); //add each Xero invoice to this list

            //for each invoice to be imported, pass in the list of invoices to factor out the line items into the correct invoice
            foreach (var AquariumInvoiceLineItem in theAquariumInvoicesToImport.OutboundInvoiceLineItems)
            {
                //pass in the invoice, then find all matching line items
                if (AquariumInvoiceLineItem.Result != "true") //then we can try and import it - security check
                {
                    //check we havent' done it already
                    int HaveWeDoneThisInvoiceAlready = (from invoice in theXeroInvoicesToImport
                                                        .Where(x => x.InvoiceNumber == AquariumInvoiceLineItem.InvoiceNumber.ToString())
                                                        select invoice).ToList().Count();

                    //we haven't imported it already -- run the proceedure to convert to xero invoice
                    if (HaveWeDoneThisInvoiceAlready < 1)
                    {
                        //convert to Xero Invoice

                        //need to check what company it is, so we can pull the correct contact
                        Datalayer.Xero.Interresolve.InterResolveXeroService aServiceInstanceToCheckTheCompany = new Datalayer.Xero.Interresolve.InterResolveXeroService(Datalayer.Xero.Interresolve.InterResolveXeroService.GetXeroOrganisationFromIRCompanyName(theAquariumInvoicesToImport.OutboundInvoiceLineItems.ElementAt(0).SageCompanyName));

                        XeroApi.Model.Invoice invoiceToAdd = OutboundInvoiceLineItemList.ConvertMultipleOutboundInvoiceLineItemsToXeroInvoice(theAquariumInvoicesToImport, AquariumInvoiceLineItem, aServiceInstanceToCheckTheCompany);

                        //Add invocie to import list
                        theXeroInvoicesToImport.Add(invoiceToAdd);

                    }

                }

            }

            ///////////////////////////////////////////////////
            //now for each invoice in the list, push to Xero
            ///////////////////////////////////////////////////

            //check the invoice company, and create the correct Xero login to that company

            for (var i = 0; i < theXeroInvoicesToImport.Count; i++)
            {

                //get the company name from the original Invoice list where invoice number = xxxxxx
                string IRCompanyName = (from Invoice in theAquariumInvoicesToImport.OutboundInvoiceLineItems
                                            .Where(x => x.InvoiceNumber == Convert.ToInt64(theXeroInvoicesToImport.ElementAt(i).InvoiceNumber))
                                        select Invoice.SageCompanyName

                                            ).Distinct().FirstOrDefault();

                string IRCompanyToPostTo = IRCompanyName;

                InterResolveXeroService.InterResolveXeroOrganisation XeroCompanyToPostTo = InterResolveXeroService.GetXeroOrganisationFromIRCompanyName(IRCompanyToPostTo);
                //Find which organsation we want to post to, and create XeroLogin class accordingly
                InterResolveXeroService aXeroService = new InterResolveXeroService(XeroCompanyToPostTo);
                //post each invoice to xero and check the result was 'OK'
                aXeroService.LoginToXero();

                var InvoiceResponse = aXeroService.XeroRepository.Create<XeroApi.Model.Invoice>(theXeroInvoicesToImport.ElementAt(i));

                //check response - write back to Aquarium that invoice was successfully imported, or not

                if (InvoiceResponse.ValidationStatus == XeroApi.Model.ValidationStatus.OK)
                {
                    Int64 TableRowID = XeroHelper.GetTableRowIDfromXeroInvoice(theXeroInvoicesToImport.ElementAt(i), theAquariumInvoicesToImport);

                    if (TableRowID != 0)
                    {
                        //call function to write back to Aquarium
                        var writeToAq = XeroHelper.XeroImportSuccessful_UpdateAquariumTableRow(TableRowID);
                    }

                }

                //tidy up
                aXeroService = null;

                //end
            }

            return View();
        }
        public void PushDummyInvoiceToAllXeroCompanies()
        {
            List<InterResolveXeroService> AllTheInterResolveCompanies = new List<InterResolveXeroService>();

            InterResolveXeroService InterResolve_LtdService = new InterResolveXeroService(InterResolveXeroService.InterResolveXeroOrganisation.InterResolve_Ltd);
            InterResolveXeroService MotorResolve_LtdService = new InterResolveXeroService(InterResolveXeroService.InterResolveXeroOrganisation.MotorResolve_Ltd);
            InterResolveXeroService InterMediation_Group_LtdService = new InterResolveXeroService(InterResolveXeroService.InterResolveXeroOrganisation.InterMediation_Group_Ltd);
            InterResolveXeroService InterResolve_Claims_LtdService = new InterResolveXeroService(InterResolveXeroService.InterResolveXeroOrganisation.InterResolve_Claims_Ltd);
            InterResolveXeroService InterResolve_Holdings_LtdService = new InterResolveXeroService(InterResolveXeroService.InterResolveXeroOrganisation.InterResolve_Holdings_Ltd);

            AllTheInterResolveCompanies.Add(InterResolve_LtdService);
            AllTheInterResolveCompanies.Add(MotorResolve_LtdService);
            AllTheInterResolveCompanies.Add(InterMediation_Group_LtdService);
            AllTheInterResolveCompanies.Add(InterResolve_Claims_LtdService);
            AllTheInterResolveCompanies.Add(InterResolve_Holdings_LtdService);

            OutboundInvoiceLineItemList someInvoices = new OutboundInvoiceLineItemList();

            someInvoices.Get();

            XeroApi.Model.Invoice anInvoice = OutboundInvoiceLineItem.ConvertSingleLineItemOutboundInvoiceToXeroInvoice(someInvoices.OutboundInvoiceLineItems.FirstOrDefault());

            foreach (var company in AllTheInterResolveCompanies)
            {
              //     Assert.IsTrue(company.PostOutboundInvoiceToXero(anInvoice));
            }
        }
        /// <summary>
        /// this maps the correct company to it's corresponding Xero Company
        /// </summary>
        public XeroApi.Model.Contact GetXeroContactFromAquariumInvoiceLineItemList(OutboundInvoiceLineItemList theAquariumLineItemList)
        {
            try{

                XeroApi.Model.Contact theXeroContact = new Contact();

                //assign the correct company based on the CompanyRef
                switch(theAquariumLineItemList.OutboundInvoiceLineItems.ElementAt(0).CompanyRef)
                {
                    case "ACR123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                          where contact.Name == "Acromas Insurance Company Ltd"
                                          select contact);
                        break;

                    case "ADM123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Admiral Insurance"
                                                                select contact);
                        break;

                    case "BRO123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Broker Direct"
                                                                 select contact);
                        break;

                    case "COV123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Covea Insurance plc"
                                                                 select contact);
                        break;

                    case "DOC123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Doctors Chambers (UK) Ltd"
                                                                 select contact);
                        break;

                    case "END123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Endsleigh Insurance Services Ltd"
                                                                 select contact);
                        break;

                    case "EQU123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Equity"
                                                                 select contact);
                        break;

                    case "LIV123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Liverpool Victoria Friendly Society"
                                                                 select contact);
                        break;

                    case "MARK123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Markerstudy"
                                                                 select contact);
                        break;

                    case "OCT123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Resolution Management Services Ltd"
                                                                 select contact);
                        break;

                    case "PRE123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Prettys Solicitors"
                                                                 select contact);
                        break;

                    case "PROV123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Covea Insurance plc"
                                                                 select contact);
                        break;

                    case "SER123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Service Underwriting Ltd"
                                                                 select contact);
                        break;

                    case "TEST123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Test"
                                                                 select contact);
                        break;

                    case "TST123":
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Test"
                                                                 select contact);
                        break;
                    default:
                        theXeroContact = (XeroApi.Model.Contact)(from contact in this.XeroRepository.Contacts
                                                                 where contact.Name == "Test"
                                                                 select contact);
                        break;

                }

                return theXeroContact;
            } catch (Exception ex)
            {
                throw ex;
            }
        }
        public void TestXeroLogin()
        {
            //  var test = InboundInvoice.GetAllAquariumPurchaseInvoiceNumbers();

            List<InterResolveXeroService> AllTheInterResolveCompanies = new List<InterResolveXeroService>();

            InterResolveXeroService InterResolve_LtdService = new InterResolveXeroService(InterResolveXeroService.InterResolveXeroOrganisation.InterResolve_Ltd);
            InterResolveXeroService MotorResolve_LtdService = new InterResolveXeroService(InterResolveXeroService.InterResolveXeroOrganisation.MotorResolve_Ltd);
            InterResolveXeroService InterMediation_Group_LtdService = new InterResolveXeroService(InterResolveXeroService.InterResolveXeroOrganisation.InterMediation_Group_Ltd);
            InterResolveXeroService InterResolve_Claims_LtdService = new InterResolveXeroService(InterResolveXeroService.InterResolveXeroOrganisation.InterResolve_Claims_Ltd);
            //    InterResolveXeroService InterResolve_Holdings_LtdService = new InterResolveXeroService(InterResolveXeroService.InterResolveXeroOrganisation.InterResolve_Holdings_Ltd);

            AllTheInterResolveCompanies.Add(InterResolve_LtdService);
            AllTheInterResolveCompanies.Add(MotorResolve_LtdService);
            AllTheInterResolveCompanies.Add(InterMediation_Group_LtdService);
            AllTheInterResolveCompanies.Add(InterResolve_Claims_LtdService);
              //      AllTheInterResolveCompanies.Add(InterResolve_Holdings_LtdService);

            OutboundInvoiceLineItemList someInvoices = new OutboundInvoiceLineItemList();

            someInvoices.Get();

            XeroApi.Model.Invoice anInvoice = OutboundInvoiceLineItem.ConvertSingleLineItemOutboundInvoiceToXeroInvoice(someInvoices.OutboundInvoiceLineItems.FirstOrDefault());

            foreach (var company in AllTheInterResolveCompanies)
            {
                company.LoginToXero();
                anInvoice.LineItems.ElementAt(0).LineAmount = 20;
                anInvoice.LineItems.ElementAt(0).UnitAmount = 20;

                XeroApi.Model.Contact theXeroContact = new XeroApi.Model.Contact();
                theXeroContact.Name = "Test Contact";

                anInvoice.Contact = theXeroContact;
                var InvoiceResponse = company.XeroRepository.Create<XeroApi.Model.Invoice>(anInvoice);
            }
        }
        /// <summary>
        /// Gets the TableRowID from a list of invoices
        /// </summary>
        /// <param name="theXeroInvoice"></param>
        /// <param name="theLineItemsToCheckAgainstAndRetriveTableRowIDFrom"></param>
        /// <returns></returns>
        public static Int64 GetTableRowIDfromXeroInvoice(XeroApi.Model.Invoice theXeroInvoice, OutboundInvoiceLineItemList theLineItemsToCheckAgainstAndRetriveTableRowIDFrom)
        {
            try
            {
                int InvoiceNumber = Convert.ToInt32(theXeroInvoice.InvoiceNumber);
                Int64 TableRowID = 0;

                for (int i = 0; i < theLineItemsToCheckAgainstAndRetriveTableRowIDFrom.OutboundInvoiceLineItems.Count; i++)
                {

                    if (theLineItemsToCheckAgainstAndRetriveTableRowIDFrom.OutboundInvoiceLineItems.ElementAt(i).InvoiceNumber == InvoiceNumber)
                    { TableRowID = theLineItemsToCheckAgainstAndRetriveTableRowIDFrom.OutboundInvoiceLineItems.ElementAt(i).TableRowID; break; }

                }

                return TableRowID;

            }

            catch(Exception ex)
            { throw ex;}
        }