using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace hukpiWinApp
{
    public partial class PartnerForm : BaseForm
    {
        //private decimal partnerId;
        private decimal regionId;
        private decimal contractTypeId;
        private decimal contractId;
        private bool existContractId;

        /// <summary>
        ///     PartnerId-val inicializált PartnerForm konstruktor, mellyel automatikusan betölti a PartnerForm a partner adatait.
        /// </summary>
        /// <param name="partnerId"></param>
        public PartnerForm(decimal partnerId)
        {
            InitializeComponent();

            hukpiDatabaseDataSetTableAdapters.PartnerDataViewTableAdapter PartnerDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.PartnerDataViewTableAdapter();
            hukpiDatabaseDataSet.PartnerDataViewDataTable partnerData = PartnerDataAdapter.GetDataByPartnerId(Convert.ToDecimal(partnerId));

            base.partnerId = partnerId;
            
            this.Text = partnerData[0]["PartnerNumber"].ToString() + " - " + partnerData[0]["Name"].ToString();
            
            loadPartnerDataToForm(partnerData);

            partnerData.Dispose();
            PartnerDataAdapter.Dispose();
        }

        /// <summary>
        ///     A megadott partnerData DataTable adatait betölti a PartnerForm-ba
        /// </summary>
        /// <param name="partnerData"></param>
        private void loadPartnerDataToForm(hukpiDatabaseDataSet.PartnerDataViewDataTable partnerData)
        {
            labelPartnerName.Text = partnerData[0]["Name"].ToString();
            textBoxPartnerNumber.Text =partnerData[0]["PartnerNumber"].ToString();
            textBoxOrderNumber.Text = partnerData[0]["OrderNumber"].ToString();
            textBoxPlace.Text = partnerData[0]["Place"].ToString();
            textBoxContractType.Text = partnerData[0]["ContractTypeName"].ToString();
            textBoxZipCode.Text = partnerData[0]["ZipCode"].ToString();
            textBoxRegionCode.Text = partnerData[0]["RegionCode"].ToString() + " - " + partnerData[0]["RegionName"].ToString();
            textBoxAddress.Text = partnerData[0]["Address"].ToString();
            textBoxLetterAddress.Text = partnerData[0]["LetterAddress"].ToString();
            textBoxOwner.Text = partnerData[0]["Owner"].ToString();

            // Néhány helyi változó beállítása
            this.regionId = Utils.getDecimalValueFromDB(partnerData[0]["RegionsId"]);
            this.contractTypeId = Utils.getDecimalValueFromDB(partnerData[0]["ContractTypesId"]);
            this.contractId = Utils.getDecimalValueFromDB(partnerData[0]["ContractId"]);

            // Attól függően, hogy lett-e már létrehozva a partnerhez szerződés, úgy állítjuk be a gombokat
            this.existContractId = !Convert.IsDBNull(partnerData[0]["ContractId"]);
            chooseOpenOrNewContract(this.existContractId);
        }

        /// <summary>
        ///     A megadott partnerId-hoz tartozó paramétereket betölti a PartnerForm-ba
        /// </summary>
        /// <param name="partnerId"></param>
        private void loadPartnerDataToForm(decimal partnerId)
        {
            hukpiDatabaseDataSetTableAdapters.PartnerDataViewTableAdapter PartnerDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.PartnerDataViewTableAdapter();
            hukpiDatabaseDataSet.PartnerDataViewDataTable partnerData = PartnerDataAdapter.GetDataByPartnerId(Convert.ToDecimal(partnerId));

            loadPartnerDataToForm(partnerData);

            partnerData.Dispose();
            PartnerDataAdapter.Dispose();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (dateTimePicker1.Checked)
            {
                MessageBox.Show(dateTimePicker1.Text);
            }
            else
            {
                MessageBox.Show("empty");
            }
        }

        public override void refreshData()
        {
            loadPartnerDataToForm(partnerId);

            Utils.setRolesToButtonsElseVisibleTrue(flowLayoutPanelOnPartnerForm, this.MdiParent);
            chooseOpenOrNewContract(this.existContractId);

        }

        private void buttonOpenDepotsForPartner_Click(object sender, EventArgs e)
        {
            ((MainForm)this.MdiParent).openNewMDIChildForm(new SearchDepotForm(partnerId));
        }

        private void buttonAddDepot_Click(object sender, EventArgs e)
        {
            ((MainForm)this.MdiParent).openNewMDIChildForm(new AddEditDepotForm(partnerId));
        }

        private void buttonAddPartner_Click(object sender, EventArgs e)
        {
            ((MainForm)this.MdiParent).openNewMDIChildForm(new AddEditPartnerForm());
        }

        private void buttonEditPartner_Click(object sender, EventArgs e)
        {
            ((MainForm)this.MdiParent).openNewMDIChildForm(new AddEditPartnerForm(partnerId));
        }

        private void PartnerForm_Load(object sender, EventArgs e)
        {
            Utils.setRolesToButtons(flowLayoutPanelOnPartnerForm, this.MdiParent);
        }

        private void chooseOpenOrNewContract(bool existsPartnerContract)
        {
            foreach (Control c in flowLayoutPanelOnPartnerForm.Controls)
            {
                if (c.Tag == null || "".Equals(c.Tag.ToString().Trim()))
                {
                    c.Visible = false;
                }
                else
                {
                    if ("21".Equals(c.Tag))
                    {
                        if (!existsPartnerContract)
                        {
                            c.Visible = false;
                        }
                    }
                    else if("22".Equals(c.Tag)){
                        if (existsPartnerContract)
                        {
                            c.Visible = false;
                        }
                    }
                }

            }
        }

        private void buttonOpenContracts_Click(object sender, EventArgs e)
        {
            ((MainForm)this.MdiParent).openNewMDIChildForm(new PartnerContractForm(partnerId, this.contractId));
        }

        private void buttonAddPartnerContract_Click(object sender, EventArgs e)
        {
            ((MainForm)this.MdiParent).openNewMDIChildForm(new AddEditPartnerContractForm(partnerId));
        }

        private bool softDeletePartner()
        {
            try
            {
                using (hukpiLINQDataContext linqContext = new hukpiLINQDataContext())
                {
                    using (var transaction = new System.Transactions.TransactionScope())
                    {
                        PartnerData partnerData = linqContext.PartnerDatas.Single(p => p.PartnerId == partnerId);

                        partnerData.StatusFlag = 'I';
                        linqContext.SubmitChanges();

                        var depotsData = from p in linqContext.DepotDatas
                                         where p.PartnerId == partnerId
                                         select p;

                        foreach (DepotData actDepotData in depotsData)
                        {
                            actDepotData.StatusFlag = 'I';
                            linqContext.SubmitChanges();
                        }
                        transaction.Complete();
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            }
        }

        private void closeDeletedWindows(decimal partnerId)
        {
            foreach (BaseForm form in MdiParent.MdiChildren)
            {
                if (form.partnerId == partnerId)
                {
                    form.Dispose();
                }
            }
        }

        private void buttonDeletePartner_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Biztosan törölni akarja a partnert?", "Törlés megerősítése...", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                if (softDeletePartner())
                {
                    ((MainForm)this.MdiParent).refreshDataInAllChildForm();
                    closeDeletedWindows(this.partnerId);
                    MessageBox.Show("Partner törölve!","Törlés",MessageBoxButtons.OK,MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Partner törlése sikertelen!", "Törlés", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
        }
    }
}
