using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using KashFlowPayPal.uk.co.kashflow.secure;
using KashFlowPayPal.Classes;
using com.paypal.soap.api;
using System.Globalization;


namespace KashFlowPayPal
{
    public partial class frmGeneral : Form
    {
        
        public ArrayList  transactionIDs;
        
        public frmGeneral()
        {
            InitializeComponent();
        }

        #region LOADING

        private void frmGeneral_Load(object sender, EventArgs e)
        {

            tabOptions.SelectTab(0);

            ColumnHeader header1 = lstTransactionsBank.Columns.Add("Account Name", 25 * Convert.ToInt32(lstTransactionsBank.Font.SizeInPoints), HorizontalAlignment.Left);
            ColumnHeader header2 = lstTransactionsBank.Columns.Add("Account Code", 25 * Convert.ToInt32(lstTransactionsBank.Font.SizeInPoints), HorizontalAlignment.Left);
            //lstPaypalBank.Columns.Add((ColumnHeader)header1.Clone());
            //lstPaypalBank.Columns.Add((ColumnHeader)header2.Clone());
            //lstPaypalBank.Columns.Add((ColumnHeader)header3.Clone());

            cmbCustomers.Items.Clear();
            cmbProducts.Items.Clear();
            cmbBankTransactionType.Items.Clear();
            lstTransactionsBank.Items.Clear();
            //lstPaypalBank.Items.Clear();

            lblMessage.Text = "PP:Konnect is loading information from KashFlow....";
            Application.DoEvents();

            PayPalConstants.LoadPayPalConstants();
            
            timer1.Enabled = true;
            timer1.Interval = 1500;
            timer1.Start();
            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //Fill Customers and Products Combobox from KashFlow
            KashFlowAPI kash = new KashFlowAPI();
            string strStatus = "";
            string strStatusDetail = "";
            if (PayPalConstants.KASH_API_USERNAME.Trim() == "" || PayPalConstants.KASH_API_PASSWORD=="")
            {
                lblMessage.Text = "Please enter your KashFlow credentials";
                Application.DoEvents();
                timer1.Enabled = false;
                return;
            }
            Customer[] cus = null;
            Product[] product = null;
            BankTXType[] txType = null;
            

            //Populate the customers drop down
            cus = KashAPI.GetCustomers();

            if (KashAPI.strStatus != "OK")
            {
                timer1.Enabled = false;
                MessageBox.Show(KashAPI.strStatusDetail, "PP:Konnect", MessageBoxButtons.OK, MessageBoxIcon.Error);
                lblMessage.Text = KashAPI.strStatusDetail;
                if (lblMessage.Text.EndsWith("access list"))
                    lnkAccesslist.Visible = true;
                else
                    lnkAccesslist.Visible = false;
                Application.DoEvents();
                return;
            }

            foreach (Customer c in cus)
            {   
                cmbCustomers.Items.Add(c.Name);
            }

            //Populate the products drop down
            product = KashAPI.GetProducts();

            if (KashAPI.strStatus != "OK")
            {
                MessageBox.Show(KashAPI.strStatusDetail, "PP:Konnect", MessageBoxButtons.OK, MessageBoxIcon.Error);
                lblMessage.Text = KashAPI.strStatusDetail;
                Application.DoEvents();
                return;
            }
            
            foreach (Product p in product)
            {
                cmbProducts.Items.Add(p.ProductName);
            }

            //Populate the bank transaction type drop down
            txType = KashAPI.GetBankTXTypes();

            if (KashAPI.strStatus != "OK")
            {
                MessageBox.Show(KashAPI.strStatusDetail, "PP:Konnect", MessageBoxButtons.OK, MessageBoxIcon.Error);
                lblMessage.Text = KashAPI.strStatusDetail;
                Application.DoEvents();
                return;
            }

            foreach (BankTXType tx in txType)
            {
                cmbBankTransactionType.Items.Add(tx.TypeName);
            }


            //load bank accounts from Kashflow
            ProgramOptions objOpt = new ProgramOptions();
            objOpt.LoadCustomerSettings();
            BankAccount[] bank = kash.GetBankAccounts(PayPalConstants.KASH_API_USERNAME, PayPalConstants.KASH_API_PASSWORD, out strStatus, out strStatusDetail);
            if (strStatus == "OK" && bank != null && bank.Length > 0)
            {


                for (int i = 0; i < bank.Length; i++)
                {
                    //if (tra.PaymentTransactions[i].Status.ToString() == "Success")
                    //{
                    ListViewItem lviTransBank = new ListViewItem(bank[i].AccountName);
                    //ListViewItem lviPaypalBank = null;
                    if(objOpt.BankAccountID.Trim()==Convert.ToString(bank[i].AccountID).Trim())
                        lviTransBank.Checked = true;

                    lviTransBank.Tag = Convert.ToString(bank[i].AccountID);
                    lviTransBank.SubItems.Add(Convert.ToString(bank[i].AccountCode));

                    lstTransactionsBank.Items.AddRange(new ListViewItem[] { lviTransBank });

                    //Create paypal bank listviewitem
                    /*lviPaypalBank = (ListViewItem)lviTransBank.Clone();
                    lviPaypalBank.Checked = false;
                    if (objOpt.PaypalBankAccountID.Trim() == Convert.ToString(bank[i].AccountID).Trim())
                        lviPaypalBank.Checked = true;
                    
                    lstPaypalBank.Items.AddRange(new ListViewItem[] { lviPaypalBank });*/
                    //}
                }
            }

            rdoAllCustomers.Checked = objOpt.AllCustomers;
            ToggleCustomerDropDown();
            if (rdoAllCustomers.Checked == false)
            {
                rdoSingleCustomer.Checked = true;
                cmbCustomers.SelectedItem = KashAPI.GetCustomerName(objOpt.CustomerName);
            }
            cmbProducts.SelectedItem = KashAPI.GetProductName(objOpt.ProductID);
            cmbBankTransactionType.SelectedItem = KashAPI.GetTxName(objOpt.BankTransactionTypeID);

            //Configure VAT tab
            if (KashAPI.isUserVATRegistered() == true)
            {
                txtVATRate.Enabled = true;
                lblNotVATRegistered.Visible = false;
            }
            else
            {
                txtVATRate.Enabled = false;
                lblNotVATRegistered.Visible = true;
            }

            txtVATRate.Text = objOpt.VATRate.ToString();
            
            
            lblMessage.Text = "";
            timer1.Enabled = false;
        }

        #endregion

        #region SAVING

        private void btnSaveTra_Click(object sender, EventArgs e)
        {
            int i = 0;
            string _transaccountID = "";
            //string _paypalaccountID = "";

            //Check to ensure that a client has been selected from the drop down if applicable
            if (rdoSingleCustomer.Checked == true)
            {
                if (cmbCustomers.Text == "")
                {
                    lblMessage.Text = "Please select a client to assign transactions to";
                    tabOptions.SelectTab(0);
                    return;
                }
            }

            //Check to ensure a product type has been selected
            if (cmbProducts.Text == "")
            {
                lblMessage.Text = "Please select a product to assign transactions to";
                tabOptions.SelectTab(0);
                return;
            }

            //Check to ensure that a transaction bank account has been selected
            foreach (ListViewItem itm in lstTransactionsBank.Items)
            {
                if (itm.Checked)
                {
                    _transaccountID = Convert.ToString(itm.Tag);
                    i += 1;
                    if (i > 1)
                    {
                        lblMessage.Text = "Please select one bank account at a time";
                        tabOptions.SelectTab(0);
                        return;

                    }
                }
            }
            if (i == 0)
            {
                lblMessage.Text = "You have not selected a transaction bank account";
                tabOptions.SelectTab(0);
                return;
            }

            //Check to ensure a Paypal fee bank account has been selected
            /*i = 0;
            foreach (ListViewItem itm in lstPaypalBank.Items)
            {
                if (itm.Checked)
                {
                    _paypalaccountID = itm.SubItems[0].Text;
                    i += 1;
                    if (i > 1)
                    {
                        lblMessage.Text = "Please select one PayPal bank account at a time";
                        tabOptions.SelectTab(1);
                        return;

                    }
                }
            }
            if (i == 0)
            {
                lblMessage.Text = "You have not selected a PayPal bank account";
                tabOptions.SelectTab(1);
                return;
            }*/

            //Check to ensure the PayPal bank transaction type has been selected
            if (cmbBankTransactionType.Text == "")
            {
                lblMessage.Text = "Please select a bank transaction type for PayPal fees";
                tabOptions.SelectTab(1);
                return;
            }

            //If VAT rate is enabled ensure the user has entered an amount
            if (txtVATRate.Enabled == true)
            {
                if (txtVATRate.Text == "")
                {
                    lblMessage.Text = "You have not entered your VAT rate";
                    tabOptions.SelectTab(2);
                    return;
                }
            }

            ProgramOptions objOpt = new ProgramOptions();

            objOpt.AllCustomers = rdoAllCustomers.Checked;
            objOpt.CustomerName = Convert.ToString(KashAPI.GetCustomerID(cmbCustomers.Text.Trim()));
            objOpt.ProductID = KashAPI.GetProductID(cmbProducts.Text.Trim());

            objOpt.BankAccountID = _transaccountID;
            //objOpt.PaypalBankAccountID = _paypalaccountID;
            objOpt.BankTransactionTypeID = KashAPI.GetTxID(cmbBankTransactionType.Text.Trim());

            objOpt.VATRate = decimal.Parse(txtVATRate.Text);
            objOpt.SaveCustomerSettings();


            //MessageBox.Show("Settings saved", "PP:Konnect", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }

        #endregion

        #region TRIGGERS

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void rdoSingleCustomer_CheckedChanged(object sender, EventArgs e)
        {
            ToggleCustomerDropDown();
        }

        private void ToggleCustomerDropDown()
        {
            if (rdoSingleCustomer.Checked)
                cmbCustomers.Enabled = true;
            else
                cmbCustomers.Enabled = false;
        }

        //Do not allow entry of non numeric characters in VAT text box
        private void txtVATRate_KeyPress(object sender, KeyPressEventArgs e)
        {
            base.OnKeyPress(e);

        NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
        string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
        string groupSeparator = numberFormatInfo.NumberGroupSeparator;
        string negativeSign = numberFormatInfo.NegativeSign;

        string keyInput = e.KeyChar.ToString();

        if (Char.IsDigit(e.KeyChar))
        {
            // Digits are OK
        }
        else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) ||
         keyInput.Equals(negativeSign))
        {
            // Decimal separator is OK
        }
        else if (e.KeyChar == '\b')
        {
            // Backspace key is OK
        }
        //    else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
        //    {
        //     // Let the edit control handle control and alt key combinations
        //    }
        else
            {
            // Swallow this invalid key and beep
            e.Handled = true;
            //    MessageBeep();
            }
        }     
   
        #endregion

        private void lnkAccesslist_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://api.kashflow.co.uk/enableAPI.asp?highlight=4");
        }

    }
}