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 DepotForm : BaseForm
    {
        //private decimal depotId;
        //private decimal partnerId;
        private decimal regionsId;

        public DepotForm(decimal depotId)
        {
            InitializeComponent();

            hukpiDatabaseDataSetTableAdapters.DepotDataViewTableAdapter DepotDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.DepotDataViewTableAdapter();
            hukpiDatabaseDataSet.DepotDataViewDataTable depotData = DepotDataAdapter.GetDataByDepotId(Convert.ToDecimal(depotId));

            this.depotId = Utils.getDecimalValueFromDB(depotData[0]["DepotId"]);
            this.partnerId = Utils.getDecimalValueFromDB(depotData[0]["PartnerId"]);
            this.regionsId = Utils.getDecimalValueFromDB(depotData[0]["RegionsId"]);

            loadDepotDataToForm(depotData);

            this.Text = depotData[0]["DepotCode"].ToString() + " - " + depotData[0]["DepotName"].ToString();

            AutoResizeAllListViewColumnWidth();
            
        }

        private void loadDepotDataToForm(hukpiDatabaseDataSet.DepotDataViewDataTable depotData)
        {
            clearAllListView();
            ListViewItem item;
            ListViewItem.ListViewSubItem subItem;

            #region Partnerfejléc kitöltése
                hukpiDatabaseDataSetTableAdapters.PartnerDataViewTableAdapter PartnerDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.PartnerDataViewTableAdapter();
                hukpiDatabaseDataSet.PartnerDataViewDataTable partnerData = PartnerDataAdapter.GetDataByPartnerId(Convert.ToDecimal(this.partnerId));

                partnerHeaderForDepot.setUCPartnerName(partnerData[0]["Name"].ToString());
                partnerHeaderForDepot.setUCPartnerNumber(partnerData[0]["PartnerNumber"].ToString());
                partnerHeaderForDepot.setUCOrderNumber(partnerData[0]["OrderNumber"].ToString());
                partnerHeaderForDepot.setUCPlace(partnerData[0]["Place"].ToString());
                partnerHeaderForDepot.setUCContractType(partnerData[0]["ContractTypeName"].ToString());
                partnerHeaderForDepot.setUCHeaderGroupBoxTitle("Partner adatok");
            #endregion

            #region Alap felrakóhely adatok betöltése
                // ListView előtti rész
                partnerHeaderForDepot.setUCTitle(depotData[0]["DepotName"].ToString());
                textBoxDepotCode.Text = depotData[0]["DepotCode"].ToString();
                textBoxCountryCode.Text = depotData[0]["RegionCode"].ToString() + " - " + depotData[0]["RegionName"].ToString();
                textBoxAddress.Text = depotData[0]["DepotAddress"].ToString();

                // ListView utáni rész
                textBoxWeighing.Text = depotData[0]["Weighing"].ToString();
                textBoxComment.Text = depotData[0]["Comments"].ToString();
                checkBoxBasedOnNotification.Checked = Utils.isCheckedFromDB(depotData[0]["isTransportByNotification"].ToString());
            #endregion

            #region Távolságok betöltése
                hukpiDatabaseDataSetTableAdapters.DistancesViewTableAdapter DistancesDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.DistancesViewTableAdapter();
                hukpiDatabaseDataSet.DistancesViewDataTable distanceData = DistancesDataAdapter.GetDataByDepotIdWithPriority(Convert.ToDecimal(this.depotId));

                foreach (hukpiDatabaseDataSet.DistancesViewRow row in distanceData)
                {
                    item = new ListViewItem(row["Distance"].ToString() + Properties.Settings.Default.distanceUnit);
                    item.Tag = row["DistanceBetweenDepotsId"].ToString();
                    subItem = new ListViewItem.ListViewSubItem(item, row["Name"].ToString());
                    
                    item.SubItems.Add(subItem);
                    listViewDistances.Items.Add(item);
                }

                distanceData.Dispose();
                DistancesDataAdapter.Dispose();
            #endregion

            #region Jellegek betöltése
            hukpiDatabaseDataSetTableAdapters.ModalitiesViewTableAdapter ModalitiesDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.ModalitiesViewTableAdapter();
            hukpiDatabaseDataSet.ModalitiesViewDataTable modalityData = ModalitiesDataAdapter.GetDataByDepotIdWithPriority(Convert.ToDecimal(this.depotId));

            foreach (hukpiDatabaseDataSet.ModalitiesViewRow row in modalityData)
            {
                item = new ListViewItem(row["ShortModality"].ToString());
                item.Tag = row["ModalityId"].ToString();
                subItem = new ListViewItem.ListViewSubItem(item, row["Modality"].ToString());

                item.SubItems.Add(subItem);
                listViewModalities.Items.Add(item);
            }

            modalityData.Dispose();
            ModalitiesDataAdapter.Dispose();
            #endregion

            #region Járatok betöltése
            hukpiDatabaseDataSetTableAdapters.RoutesViewTableAdapter RoutesDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.RoutesViewTableAdapter();
            hukpiDatabaseDataSet.RoutesViewDataTable routeData = RoutesDataAdapter.GetDataByDepotIdWithPriority(Convert.ToDecimal(this.depotId));

            foreach (hukpiDatabaseDataSet.RoutesViewRow row in routeData)
            {
                item = new ListViewItem(row["Code"].ToString());
                item.Tag = row["RoutesId"].ToString();
                subItem = new ListViewItem.ListViewSubItem(item, row["Details"].ToString());

                item.SubItems.Add(subItem);
                listViewRouteCodes.Items.Add(item);
            }

            routeData.Dispose();
            RoutesDataAdapter.Dispose();
            #endregion

            #region Konténerek betöltése
            hukpiDatabaseDataSetTableAdapters.DepotContainersViewTableAdapter DepotContainersDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.DepotContainersViewTableAdapter();
            hukpiDatabaseDataSet.DepotContainersViewDataTable depotContainerData = DepotContainersDataAdapter.GetDataByDepotId(Convert.ToDecimal(this.depotId));

            foreach (hukpiDatabaseDataSet.DepotContainersViewRow row in depotContainerData)
            {
                item = new ListViewItem(row["ContainerName"].ToString());
                item.Tag = row["DepotContainersId"].ToString();
                subItem = new ListViewItem.ListViewSubItem(item, row["Number"].ToString());

                item.SubItems.Add(subItem);
                listViewContainers.Items.Add(item);
            }

            depotContainerData.Dispose();
            DepotContainersDataAdapter.Dispose();
            #endregion

            #region Osztályok betöltése
                string[] ClassNumbers = new string[] { "I", "II", "III", "IIIB" };
                hukpiDatabaseDataSetTableAdapters.DepotClassesViewTableAdapter DepotClassesDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.DepotClassesViewTableAdapter();
                hukpiDatabaseDataSet.DepotClassesViewDataTable depotClassesData;

                foreach (string actClassNumber in ClassNumbers)
                {
                    depotClassesData = DepotClassesDataAdapter.GetDataByDepotIdAndClassNumber(actClassNumber, Convert.ToDecimal(this.depotId));

                    foreach (hukpiDatabaseDataSet.DepotClassesViewRow row in depotClassesData)
                    {
                        item = new ListViewItem(row["ItemNumber"].ToString());
                        item.Tag = row["ClassesForDepotsId"].ToString();
                        
                        subItem = new ListViewItem.ListViewSubItem(item, row["ItemName"].ToString());
                        item.SubItems.Add(subItem);
                        
                        subItem = new ListViewItem.ListViewSubItem(item, row["ProcessingCode"].ToString());
                        item.SubItems.Add(subItem);

                        if ("I".Equals(actClassNumber))
                        {
                            listViewCategoryI.Items.Add(item);
                        }
                        else if ("II".Equals(actClassNumber))
                        {
                            listViewCategoryII.Items.Add(item);
                        }
                        else if ("III".Equals(actClassNumber))
                        {
                            listViewCategoryIII.Items.Add(item);
                        }
                        else if ("IIIB".Equals(actClassNumber))
                        {
                            listViewCategoryIIIB.Items.Add(item);
                        }
                        else
                        {
                            throw new Exception("Nem megfelelő osztály szám!");
                        }
                    }
                }

                DepotClassesDataAdapter.Dispose();
            #endregion

            #region Szállítási adatok betöltése
                setTransportDataOnForm(Convert.ToDecimal(this.depotId));
            #endregion
        }

        private void loadDepotDataToForm(decimal depotId)
        {
            hukpiDatabaseDataSetTableAdapters.DepotDataViewTableAdapter DepotDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.DepotDataViewTableAdapter();
            hukpiDatabaseDataSet.DepotDataViewDataTable depotData = DepotDataAdapter.GetDataByDepotId(depotId);

            loadDepotDataToForm(depotData);
        }

        private void setTransportDataOnForm(decimal depotId)
        {
            hukpiDatabaseDataSetTableAdapters.DefaultTransportDaysTableAdapter DefaultTransDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.DefaultTransportDaysTableAdapter();
            hukpiDatabaseDataSet.DefaultTransportDaysDataTable defaultTransData = DefaultTransDataAdapter.GetDataByDepotId(depotId);

            int index = 0;

            foreach (hukpiDatabaseDataSet.DefaultTransportDaysRow row in defaultTransData)
            {
                if (index > 3)
                {
                    throw new Exception("Túl sok szállítási adat tartozik a felrakóhoz az adatbázisban!");
                }
                if (Utils.isCheckedFromDB(row["isWinter"].ToString()))
                {
                    textBoxWinterWeekly.Text = row["weeklyTransport"].ToString();
                    checkBoxWMon.Checked = Utils.isCheckedFromDB(row["monday"].ToString());
                    checkBoxWTue.Checked = Utils.isCheckedFromDB(row["tuesday"].ToString());
                    checkBoxWWed.Checked = Utils.isCheckedFromDB(row["wednesday"].ToString());
                    checkBoxWThu.Checked = Utils.isCheckedFromDB(row["thursday"].ToString());
                    checkBoxWFri.Checked = Utils.isCheckedFromDB(row["friday"].ToString());
                    checkBoxWSat.Checked = Utils.isCheckedFromDB(row["saturday"].ToString());
                    checkBoxWSun.Checked = Utils.isCheckedFromDB(row["sunday"].ToString());
                }
                else
                {
                    textBoxSummerWeekly.Text = row["weeklyTransport"].ToString();
                    checkBoxSMon.Checked = Utils.isCheckedFromDB(row["monday"].ToString());
                    checkBoxSTue.Checked = Utils.isCheckedFromDB(row["tuesday"].ToString());
                    checkBoxSWed.Checked = Utils.isCheckedFromDB(row["wednesday"].ToString());
                    checkBoxSThu.Checked = Utils.isCheckedFromDB(row["thursday"].ToString());
                    checkBoxSFri.Checked = Utils.isCheckedFromDB(row["friday"].ToString());
                    checkBoxSSat.Checked = Utils.isCheckedFromDB(row["saturday"].ToString());
                    checkBoxSSun.Checked = Utils.isCheckedFromDB(row["sunday"].ToString());
                }

                index++;
            }

            defaultTransData.Dispose();
            DefaultTransDataAdapter.Dispose();
        }

        public override void refreshData()
        {
            loadDepotDataToForm(this.depotId);
        }

        private void clearAllListView()
        {
            listViewDistances.Items.Clear();
            listViewModalities.Items.Clear();
            listViewRouteCodes.Items.Clear();
            listViewContainers.Items.Clear();

            listViewCategoryI.Items.Clear();
            listViewCategoryII.Items.Clear();
            listViewCategoryIII.Items.Clear();
            listViewCategoryIIIB.Items.Clear();
        }

        public void AutoResizeAllListViewColumnWidth()
        {
            listViewCategoryIIIB.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            listViewCategoryI.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            listViewCategoryII.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            listViewCategoryIII.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
        }

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

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

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

        private void buttonAddContract_Click(object sender, EventArgs e)
        {
            ((MainForm)this.MdiParent).openNewMDIChildForm(new AddEditDepotContractForm(this.depotId, this.partnerId));
        }

        private void DepotForm_Load(object sender, EventArgs e)
        {
            Utils.setRolesToButtons(flowLayoutPanelOnDepotForm, this.MdiParent);

        }

        private bool softDeleteDepot()
        {
            try
            {
                using (hukpiLINQDataContext linqContext = new hukpiLINQDataContext())
                {
                    using (var transaction = new System.Transactions.TransactionScope())
                    {
                        DepotData depotData = linqContext.DepotDatas.Single(p => p.DepotId == depotId);
                        depotData.StatusFlag = 'I';
                        linqContext.SubmitChanges();
                        
                        transaction.Complete();
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            }
        }

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

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