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 AddEditDepotForm : BaseForm
    {
        private bool isNewRecord = false;

        //private decimal depotId;
        //private decimal partnerId;

        private List<decimal> needsToDeleteDistances;
        private List<decimal> needsToDeleteModalities;
        private List<decimal> needsToDeleteRoutes;
        private List<decimal> needsToDeleteContainers;
        private List<decimal> needsToDeleteCategoryI;
        private List<decimal> needsToDeleteCategoryII;
        private List<decimal> needsToDeleteCategoryIII;
        private List<decimal> needsToDeleteCategoryIIIB;

        public AddEditDepotForm(decimal partnerId)
        {
            InitializeComponent();
            fillComboBoxRegion();

            this.isNewRecord = true;
            this.partnerId = partnerId;

            this.Text = "Új felrakóhely felvitele";
            loadPartnerHeaderToForm(partnerId);
        }

        public AddEditDepotForm(decimal depotId, decimal partnerId)
        {
            InitializeComponent();
            fillComboBoxRegion();

            this.isNewRecord = false;
            this.partnerId = partnerId;
            this.depotId = depotId;

            this.Text = "Felrakóhely módosítása";

            loadPartnerHeaderToForm(partnerId);
            loadDepotDataToForm(depotId);
        }

        private void fillComboBoxRegion()
        {
            comboBoxCountryCode.DataSource = Utils.getRegionsForCombo();
            comboBoxCountryCode.DisplayMember = "Description";
            comboBoxCountryCode.ValueMember =  "Id";

        }

        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();
        }

        private void loadPartnerHeaderToForm(decimal partnerId)
        {
            hukpiDatabaseDataSetTableAdapters.PartnerDataViewTableAdapter PartnerDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.PartnerDataViewTableAdapter();
            hukpiDatabaseDataSet.PartnerDataViewDataTable partnerData = PartnerDataAdapter.GetDataByPartnerId(partnerId);

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

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

            clearAllListView();
            ListViewItem item;
            ListViewItem.ListViewSubItem subItem;

            #region Alap felrakóhely adatok betöltése
            // ListView előtti rész
            partnerHeader1.setUCTitle(depotData[0]["DepotName"].ToString());
            textBoxDepotName.Text = depotData[0]["DepotName"].ToString();
            textBoxDepotCode.Text = depotData[0]["DepotCode"].ToString();
            comboBoxCountryCode.SelectedValue = Utils.getIntValueFromDB(depotData[0]["RegionsId"]);
            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));

            needsToDeleteDistances = new List<decimal>();

            foreach (hukpiDatabaseDataSet.DistancesViewRow row in distanceData)
            {
                needsToDeleteDistances.Add(Utils.getDecimalValueFromDB(row["DistanceBetweenDepotsId"]));

                item = new ListViewItem(row["Distance"].ToString());
                item.Tag = row["DistanceBetweenDepotsId"].ToString();
                subItem = new ListViewItem.ListViewSubItem(item, row["Name"].ToString());
                subItem.Tag = row["CompanyDepotsId"].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));

            needsToDeleteModalities = new List<decimal>();

            foreach (hukpiDatabaseDataSet.ModalitiesViewRow row in modalityData)
            {
                needsToDeleteModalities.Add(Utils.getDecimalValueFromDB(row["DepotsAndModalitiesId"]));

                item = new ListViewItem(row["ShortModality"].ToString());
                item.Tag = row["DepotsAndModalitiesId"].ToString();
                subItem = new ListViewItem.ListViewSubItem(item, row["Modality"].ToString());
                subItem.Tag = row["ModalityId"].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));

            needsToDeleteRoutes = new List<decimal>();

            foreach (hukpiDatabaseDataSet.RoutesViewRow row in routeData)
            {
                needsToDeleteRoutes.Add(Utils.getDecimalValueFromDB(row["RoutesId"]));

                item = new ListViewItem(row["Code"].ToString());
                item.Tag = row["RoutesId"].ToString();
                subItem = new ListViewItem.ListViewSubItem(item, row["Details"].ToString());
                subItem.Tag = row["RouteCodesId"].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));

            needsToDeleteContainers = new List<decimal>();

            foreach (hukpiDatabaseDataSet.DepotContainersViewRow row in depotContainerData)
            {
                needsToDeleteContainers.Add(Utils.getDecimalValueFromDB(row["DepotContainersId"]));

                item = new ListViewItem(row["ContainerName"].ToString());
                item.Tag = row["DepotContainersId"].ToString();
                subItem = new ListViewItem.ListViewSubItem(item, row["Number"].ToString());
                subItem.Tag = row["ContainersId"].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;

                needsToDeleteCategoryI = new List<decimal>();
                needsToDeleteCategoryII = new List<decimal>();
                needsToDeleteCategoryIII = new List<decimal>();
                needsToDeleteCategoryIIIB = new List<decimal>();

                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());
                        subItem.Tag = row["ClassesId"].ToString();
                        item.SubItems.Add(subItem);

                        subItem = new ListViewItem.ListViewSubItem(item, row["ProcessingCode"].ToString());
                        subItem.Tag = row["ProcessingCodesId"].ToString();
                        item.SubItems.Add(subItem);

                        if ("I".Equals(actClassNumber))
                        {
                            needsToDeleteCategoryI.Add(Utils.getDecimalValueFromDB(row["ClassesForDepotsId"]));

                            listViewCategoryI.Items.Add(item);
                        }
                        else if ("II".Equals(actClassNumber))
                        {
                            needsToDeleteCategoryII.Add(Utils.getDecimalValueFromDB(row["ClassesForDepotsId"]));

                            listViewCategoryII.Items.Add(item);
                        }
                        else if ("III".Equals(actClassNumber))
                        {
                            needsToDeleteCategoryIII.Add(Utils.getDecimalValueFromDB(row["ClassesForDepotsId"]));

                            listViewCategoryIII.Items.Add(item);
                        }
                        else if ("IIIB".Equals(actClassNumber))
                        {
                            needsToDeleteCategoryIIIB.Add(Utils.getDecimalValueFromDB(row["ClassesForDepotsId"]));

                            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 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();
        }

        private void AddEditDepotForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (Utils.isCancelAddEditFormClose(this))
            {
                e.Cancel = true;
            }
        }

        private void saveDepot()
        {
            if (this.isNewRecord)
            {
                decimal newDepotId = saveNewDepot();
                MessageBox.Show("Sikeres mentés!");
                ((MainForm)this.MdiParent).openNewMDIChildForm(new DepotForm(newDepotId));
            }
            else
            {
                saveModifiedDepot(); 
                MessageBox.Show("Sikeres mentés!");
            }

            
            ((MainForm)this.MdiParent).refreshDataInAllChildForm();
            this.Dispose();
        }

        private decimal saveNewDepot()
        {
            decimal newDepotId;

            using (hukpiLINQDataContext linqContext = new hukpiLINQDataContext())
            {
                using (var transaction = new System.Transactions.TransactionScope())
                {
                    int index;
                    DepotData depotData = new DepotData();

                    #region Alap Felrakó adatok mentése
                    depotData.PartnerId = this.partnerId;
                    depotData.DepotName = textBoxDepotName.Text;
                    depotData.DepotCode = textBoxDepotCode.Text;
                    depotData.DepotAddress = textBoxAddress.Text;
                    depotData.StatusFlag = 'A';

                    if ((int)comboBoxCountryCode.SelectedValue == 0)
                    {
                        depotData.RegionsId = null;
                    }
                    else
                    {
                        depotData.RegionsId = Convert.ToDecimal(comboBoxCountryCode.SelectedValue);

                    }
                    // ListView-k utáni rész
                    depotData.Weighing = textBoxWeighing.Text;
                    depotData.Comments = textBoxComment.Text;

                    // depotData.isTransportByNotification
                    if (checkBoxBasedOnNotification.Checked)
                    {
                        depotData.isTransportByNotification = Convert.ToChar(Properties.Settings.Default.DBYesChar);
                    }
                    else
                    {
                        depotData.isTransportByNotification = Convert.ToChar(Properties.Settings.Default.DBNoChar);
                    }
                    linqContext.DepotDatas.InsertOnSubmit(depotData);
                    #endregion

                    #region Távolságok mentése
                    DistanceBetweenDepot distanceData;

                    index = 1;

                    foreach (ListViewItem item in listViewDistances.Items)
                    {
                        distanceData = new DistanceBetweenDepot();
                        distanceData.DepotData = depotData;
                        distanceData.Distance = Convert.ToDecimal(item.Text);
                        distanceData.CompanyDepotsId = Convert.ToDecimal(item.SubItems[1].Tag);
                        distanceData.Priority = index++;
                        
                        linqContext.DistanceBetweenDepots.InsertOnSubmit(distanceData);
                   
                        linqContext.SubmitChanges();
                    }
                    #endregion

                    #region Jellegek mentése
                    DepotsAndModality modalityData;

                    index = 1;

                    foreach (ListViewItem item in listViewModalities.Items)
                    {
                        modalityData = new DepotsAndModality();
                        modalityData.DepotData = depotData;
                        modalityData.ModalityId = Convert.ToDecimal(item.SubItems[1].Tag);
                        modalityData.Priority = index++;

                        linqContext.DepotsAndModalities.InsertOnSubmit(modalityData);
                        
                        linqContext.SubmitChanges();
                    }
                    #endregion

                    #region Járatok mentése
                    Route routeData;

                    index = 1;

                    foreach (ListViewItem item in listViewRouteCodes.Items)
                    {
                        routeData = new Route();
                        routeData.DepotData = depotData;
                        routeData.RouteCodesId = Convert.ToDecimal(item.SubItems[1].Tag);
                        routeData.Priority = index++;

                        linqContext.Routes.InsertOnSubmit(routeData);
                        
                        linqContext.SubmitChanges();
                    }
                    #endregion

                    #region Konténerek mentése
                    DepotContainer containerData;

                    index = 1;

                    foreach (ListViewItem item in listViewContainers.Items)
                    {
                        containerData = new DepotContainer();
                        containerData.DepotData = depotData;
                        containerData.ContainersId = Convert.ToDecimal(item.SubItems[1].Tag);
                        containerData.Number = Convert.ToDecimal(item.SubItems[1].Text);
                            
                        linqContext.DepotContainers.InsertOnSubmit(containerData);
                        
                        linqContext.SubmitChanges();
                    }
                    #endregion

                    #region Osztályok mentése
                    ClassesForDepot classesData;

                    string[] ClassNumbers = new string[] { "I", "II", "III", "IIIB" };

                    ListView actListView;

                    foreach (string actClassNumber in ClassNumbers)
                    {
                        switch (actClassNumber)
                        {
                            case "I":
                                actListView = listViewCategoryI;
                                break;
                            case "II":
                                actListView = listViewCategoryII;
                                break;
                            case "III":
                                actListView = listViewCategoryIII;
                                break;
                            case "IIIB":
                                actListView = listViewCategoryIIIB;
                                break;
                            default:
                                throw new Exception("Nem létező osztály kategória!");
                        }

                        index = 1;

                        foreach (ListViewItem item in actListView.Items)
                        {
                            classesData = new ClassesForDepot();
                            classesData.DepotData = depotData;
                            classesData.ClassesId = Convert.ToDecimal(item.SubItems[1].Tag);
                            classesData.ProcessingCodesId = Convert.ToDecimal(item.SubItems[2].Tag);
                                
                            linqContext.ClassesForDepots.InsertOnSubmit(classesData);
                            
                            linqContext.SubmitChanges();
                        }
                    }
                    #endregion

                    #region Szállítások mentése
                    // Téli szállítások
                    DefaultTransportDay defaultTransportDaysWinter = new DefaultTransportDay();
                    defaultTransportDaysWinter.isWinter = Convert.ToChar(Properties.Settings.Default.DBYesChar);
                    defaultTransportDaysWinter.DepotData = depotData;

                    defaultTransportDaysWinter.monday = Utils.getDBValueForCheckBox(checkBoxWMon.Checked);
                    defaultTransportDaysWinter.tuesday = Utils.getDBValueForCheckBox(checkBoxWTue.Checked);
                    defaultTransportDaysWinter.wednesday = Utils.getDBValueForCheckBox(checkBoxWWed.Checked);
                    defaultTransportDaysWinter.thursday = Utils.getDBValueForCheckBox(checkBoxWThu.Checked);
                    defaultTransportDaysWinter.friday = Utils.getDBValueForCheckBox(checkBoxWFri.Checked);
                    defaultTransportDaysWinter.saturday = Utils.getDBValueForCheckBox(checkBoxWSat.Checked);
                    defaultTransportDaysWinter.sunday = Utils.getDBValueForCheckBox(checkBoxWSun.Checked);

                    if ("".Equals(textBoxWinterWeekly.Text.Trim()))
                    {
                        defaultTransportDaysWinter.weeklyTransport = null;
                    }
                    else
                    {
                        defaultTransportDaysWinter.weeklyTransport = Convert.ToDecimal(textBoxWinterWeekly.Text);
                    }
                    linqContext.DefaultTransportDays.InsertOnSubmit(defaultTransportDaysWinter);

                    // Nyári szállítások
                    DefaultTransportDay defaultTransportDaysSummer = new DefaultTransportDay();
                    defaultTransportDaysSummer.isWinter = Convert.ToChar(Properties.Settings.Default.DBNoChar);
                    defaultTransportDaysSummer.DepotData = depotData;

                    defaultTransportDaysSummer.monday = Utils.getDBValueForCheckBox(checkBoxSMon.Checked);
                    defaultTransportDaysSummer.tuesday = Utils.getDBValueForCheckBox(checkBoxSTue.Checked);
                    defaultTransportDaysSummer.wednesday = Utils.getDBValueForCheckBox(checkBoxSWed.Checked);
                    defaultTransportDaysSummer.thursday = Utils.getDBValueForCheckBox(checkBoxSThu.Checked);
                    defaultTransportDaysSummer.friday = Utils.getDBValueForCheckBox(checkBoxSFri.Checked);
                    defaultTransportDaysSummer.saturday = Utils.getDBValueForCheckBox(checkBoxSSat.Checked);
                    defaultTransportDaysSummer.sunday = Utils.getDBValueForCheckBox(checkBoxSSun.Checked);


                    if ("".Equals(textBoxSummerWeekly.Text.Trim()))
                    {
                        defaultTransportDaysSummer.weeklyTransport = null;
                    }
                    else
                    {
                        defaultTransportDaysSummer.weeklyTransport = Convert.ToDecimal(textBoxSummerWeekly.Text);
                    }
                    
                    linqContext.DefaultTransportDays.InsertOnSubmit(defaultTransportDaysSummer);

                    linqContext.SubmitChanges();
                    #endregion

                    transaction.Complete();
                    newDepotId = Convert.ToDecimal(depotData.DepotId);
                }
            }
           
            return newDepotId;
        }

        private decimal saveModifiedDepot()
        {
            decimal modifiedDepotId;

            using (hukpiLINQDataContext linqContext = new hukpiLINQDataContext())
            {
                using (var transaction = new System.Transactions.TransactionScope())
                {
                    int index;
                    DepotData depotData = linqContext.DepotDatas.Single(p => p.DepotId == this.depotId);

                    #region Alap Felrakó adatok mentése
                        depotData.DepotName = textBoxDepotName.Text;
                        depotData.DepotCode = textBoxDepotCode.Text;
                        depotData.DepotAddress = textBoxAddress.Text;
                        depotData.StatusFlag = 'A';

                        if ((int)comboBoxCountryCode.SelectedValue == 0)
                        {
                            depotData.RegionsId = null;
                        }
                        else
                        {
                            depotData.RegionsId = Convert.ToDecimal(comboBoxCountryCode.SelectedValue);

                        }
                        // ListView-k utáni rész
                        depotData.Weighing = textBoxWeighing.Text;
                        depotData.Comments = textBoxComment.Text;

                        // depotData.isTransportByNotification
                        if (checkBoxBasedOnNotification.Checked)
                        {
                            depotData.isTransportByNotification = Convert.ToChar(Properties.Settings.Default.DBYesChar);
                        }
                        else
                        {
                            depotData.isTransportByNotification = Convert.ToChar(Properties.Settings.Default.DBNoChar);
                        }
                    #endregion

                    #region Távolságok mentése
                        DistanceBetweenDepot distanceData;

                        index = 1;

                        foreach (ListViewItem item in listViewDistances.Items)
                        {
                            if (item.Tag == null || "".Equals(item.Tag.ToString().Trim()))
                            {
                                distanceData = new DistanceBetweenDepot();
                                distanceData.DepotData = depotData;
                                distanceData.Distance = Convert.ToDecimal(item.Text);
                                distanceData.CompanyDepotsId = Convert.ToDecimal(item.SubItems[1].Tag);
                                distanceData.Priority = index++;
                                linqContext.DistanceBetweenDepots.InsertOnSubmit(distanceData);
                            }
                            else
                            {
                                needsToDeleteDistances.Remove(Convert.ToDecimal(item.Tag));

                                distanceData = linqContext.DistanceBetweenDepots.Single(p => p.DistanceBetweenDepotsId == Convert.ToDecimal(item.Tag));
                                distanceData.Distance = Convert.ToDecimal(item.Text);
                                distanceData.CompanyDepotsId = Convert.ToDecimal(item.SubItems[1].Tag);
                                distanceData.Priority = index++;
                            }

                            linqContext.SubmitChanges();
                        }

                        foreach (decimal needsToDeleteItem in needsToDeleteDistances)
                        {
                            distanceData = linqContext.DistanceBetweenDepots.Single(p => p.DistanceBetweenDepotsId == needsToDeleteItem);
                            linqContext.DistanceBetweenDepots.DeleteOnSubmit(distanceData);
                            linqContext.SubmitChanges();
                        }
                    #endregion

                    #region Jellegek mentése
                        DepotsAndModality modalityData;

                        index = 1;

                        foreach (ListViewItem item in listViewModalities.Items)
                        {
                            if (item.Tag == null || "".Equals(item.Tag.ToString().Trim()))
                            {
                                modalityData = new DepotsAndModality();
                                modalityData.DepotData = depotData;
                                modalityData.ModalityId = Convert.ToDecimal(item.SubItems[1].Tag);
                                modalityData.Priority = index++;

                                linqContext.DepotsAndModalities.InsertOnSubmit(modalityData);
                            }
                            else
                            {
                                needsToDeleteModalities.Remove(Convert.ToDecimal(item.Tag));

                                modalityData = linqContext.DepotsAndModalities.Single(p => p.DepotsAndModalitiesId == Convert.ToDecimal(item.Tag));
                                modalityData.ModalityId = Convert.ToDecimal(item.SubItems[1].Tag);
                                modalityData.Priority = index++;
                            }

                            linqContext.SubmitChanges();
                        }

                        foreach (decimal needsToDeleteItem in needsToDeleteModalities)
                        {
                            modalityData = linqContext.DepotsAndModalities.Single(p => p.DepotsAndModalitiesId == needsToDeleteItem);
                            linqContext.DepotsAndModalities.DeleteOnSubmit(modalityData);
                            linqContext.SubmitChanges();
                        }
                    #endregion

                    #region Járatok mentése
                        Route routeData;

                        index = 1;

                        foreach (ListViewItem item in listViewRouteCodes.Items)
                        {
                            if (item.Tag == null || "".Equals(item.Tag.ToString().Trim()))
                            {
                                routeData = new Route();
                                routeData.DepotData = depotData;
                                routeData.RouteCodesId = Convert.ToDecimal(item.SubItems[1].Tag);
                                routeData.Priority = index++;

                                linqContext.Routes.InsertOnSubmit(routeData);
                            }
                            else
                            {
                                needsToDeleteRoutes.Remove(Convert.ToDecimal(item.Tag));

                                routeData = linqContext.Routes.Single(p => p.RoutesId == Convert.ToDecimal(item.Tag));
                                routeData.RouteCodesId = Convert.ToDecimal(item.SubItems[1].Tag);
                                routeData.Priority = index++;
                            }

                            linqContext.SubmitChanges();
                        }

                        foreach (decimal needsToDeleteItem in needsToDeleteRoutes)
                        {
                            routeData = linqContext.Routes.Single(p => p.RouteCodesId == needsToDeleteItem);
                            linqContext.Routes.DeleteOnSubmit(routeData);
                            linqContext.SubmitChanges();
                        }
                    #endregion

                    #region Konténerek mentése
                        DepotContainer containerData;

                        index = 1;

                        foreach (ListViewItem item in listViewContainers.Items)
                        {
                            if (item.Tag == null || "".Equals(item.Tag.ToString().Trim()))
                            {
                                containerData = new DepotContainer();
                                containerData.DepotData = depotData;
                                containerData.ContainersId = Convert.ToDecimal(item.SubItems[1].Tag);
                                containerData.Number = Convert.ToDecimal(item.SubItems[1].Text);
                                linqContext.DepotContainers.InsertOnSubmit(containerData);
                            }
                            else
                            {
                                needsToDeleteContainers.Remove(Convert.ToDecimal(item.Tag));

                                containerData = linqContext.DepotContainers.Single(p => p.DepotContainersId == Convert.ToDecimal(item.Tag));
                                containerData.ContainersId = Convert.ToDecimal(item.SubItems[1].Tag);
                                containerData.Number = Convert.ToDecimal(item.SubItems[1].Text);
                            }

                            linqContext.SubmitChanges();
                        }

                        foreach (decimal needsToDeleteItem in needsToDeleteContainers)
                        {
                            containerData = linqContext.DepotContainers.Single(p => p.DepotContainersId == needsToDeleteItem);
                            linqContext.DepotContainers.DeleteOnSubmit(containerData);
                            linqContext.SubmitChanges();
                        }
                    #endregion

                    #region Osztályok mentése
                        ClassesForDepot classesData;

                        string[] ClassNumbers = new string[] { "I", "II", "III", "IIIB" };

                        ListView actListView;

                        List<decimal> needsToDeleteActCategory;

                        foreach (string actClassNumber in ClassNumbers)
                        {
                            switch (actClassNumber)
                            {
                                case "I": 
                                    actListView = listViewCategoryI;
                                    needsToDeleteActCategory = needsToDeleteCategoryI.ToArray<decimal>().ToList<decimal>();
                                    break;
                                case "II" :
                                    actListView = listViewCategoryII;
                                    needsToDeleteActCategory = needsToDeleteCategoryII.ToArray<decimal>().ToList<decimal>();
                                    break;
                                case "III":
                                    actListView = listViewCategoryIII;
                                    needsToDeleteActCategory = needsToDeleteCategoryIII.ToArray<decimal>().ToList<decimal>();
                                    break;
                                case "IIIB":
                                    actListView = listViewCategoryIIIB;
                                    needsToDeleteActCategory = needsToDeleteCategoryIIIB.ToArray<decimal>().ToList<decimal>();
                                    break;
                                default :
                                    throw new Exception("Nem létező osztály kategória!");
                            }
                            
                            index = 1;

                            foreach (ListViewItem item in actListView.Items)
                            {
                                if (item.Tag == null || "".Equals(item.Tag.ToString().Trim()))
                                {
                                    classesData = new ClassesForDepot();
                                    classesData.DepotData = depotData;
                                    classesData.ClassesId = Convert.ToDecimal(item.SubItems[1].Tag);
                                    classesData.ProcessingCodesId = Convert.ToDecimal(item.SubItems[2].Tag);
                                    linqContext.ClassesForDepots.InsertOnSubmit(classesData);
                                }
                                else
                                {
                                    needsToDeleteActCategory.Remove(Convert.ToDecimal(item.Tag));

                                    classesData = linqContext.ClassesForDepots.Single(p => p.ClassesForDepotsId == Convert.ToDecimal(item.Tag));
                                    classesData.ClassesId = Convert.ToDecimal(item.SubItems[1].Tag);
                                    classesData.ProcessingCodesId = Convert.ToDecimal(item.SubItems[2].Tag);
                                }

                                linqContext.SubmitChanges();
                            }

                            foreach (decimal needsToDeleteItem in needsToDeleteActCategory)
                            {
                                classesData = linqContext.ClassesForDepots.Single(p => p.ClassesForDepotsId == needsToDeleteItem);
                                linqContext.ClassesForDepots.DeleteOnSubmit(classesData);
                                linqContext.SubmitChanges();
                            }
                        }
                    #endregion

                    #region Szállítások mentése
                        // Téli szállítások
                        DefaultTransportDay defaultTransportDaysWinter = linqContext.DefaultTransportDays.Single(p => p.DepotId == this.depotId && p.isWinter == Convert.ToChar(Properties.Settings.Default.DBYesChar));
                        defaultTransportDaysWinter.monday = Utils.getDBValueForCheckBox(checkBoxWMon.Checked);
                        defaultTransportDaysWinter.tuesday = Utils.getDBValueForCheckBox(checkBoxWTue.Checked);
                        defaultTransportDaysWinter.wednesday = Utils.getDBValueForCheckBox(checkBoxWWed.Checked);
                        defaultTransportDaysWinter.thursday = Utils.getDBValueForCheckBox(checkBoxWThu.Checked);
                        defaultTransportDaysWinter.friday = Utils.getDBValueForCheckBox(checkBoxWFri.Checked);
                        defaultTransportDaysWinter.saturday = Utils.getDBValueForCheckBox(checkBoxWSat.Checked);
                        defaultTransportDaysWinter.sunday = Utils.getDBValueForCheckBox(checkBoxWSun.Checked);

                        if ("".Equals(textBoxWinterWeekly.Text.Trim()))
                        {
                            defaultTransportDaysWinter.weeklyTransport = null;
                        }
                        else
                        {
                            defaultTransportDaysWinter.weeklyTransport = Convert.ToDecimal(textBoxWinterWeekly.Text);
                        }

                        // Nyári szállítások
                        DefaultTransportDay defaultTransportDaysSummer = linqContext.DefaultTransportDays.Single(p => p.DepotId == this.depotId && p.isWinter == Convert.ToChar(Properties.Settings.Default.DBNoChar));
                        defaultTransportDaysSummer.monday = Utils.getDBValueForCheckBox(checkBoxSMon.Checked);
                        defaultTransportDaysSummer.tuesday = Utils.getDBValueForCheckBox(checkBoxSTue.Checked);
                        defaultTransportDaysSummer.wednesday = Utils.getDBValueForCheckBox(checkBoxSWed.Checked);
                        defaultTransportDaysSummer.thursday = Utils.getDBValueForCheckBox(checkBoxSThu.Checked);
                        defaultTransportDaysSummer.friday = Utils.getDBValueForCheckBox(checkBoxSFri.Checked);
                        defaultTransportDaysSummer.saturday = Utils.getDBValueForCheckBox(checkBoxSSat.Checked);
                        defaultTransportDaysSummer.sunday = Utils.getDBValueForCheckBox(checkBoxSSun.Checked);

                        if ("".Equals(textBoxSummerWeekly.Text.Trim()))
                        {
                            defaultTransportDaysSummer.weeklyTransport = null;
                        }
                        else
                        {
                            defaultTransportDaysSummer.weeklyTransport = Convert.ToDecimal(textBoxSummerWeekly.Text);
                        }

                        linqContext.SubmitChanges();
                    #endregion

                    transaction.Complete();
                    modifiedDepotId = Convert.ToDecimal(depotData.DepotId);
                }
            }

            return modifiedDepotId;
        }

        private void saveLayoutForDepot_CancelButtonClick()
        {
            this.Dispose();
        }

        private bool validateForm()
        {
            bool isValidDepotName = validateDepotName();
            bool isValidSummerWeekly = validateSummerWeekly();
            bool isValidWinterWeekly = validateWinterWeekly();

            return isValidDepotName && isValidSummerWeekly && isValidWinterWeekly;
        }

        private void saveLayoutForDepot_SaveButtonClick()
        {
            if (validateForm())
            {
                saveDepot();
            }
            else
            {
                MessageBox.Show(ErrorMessages.Default.invalidFormInputData);
            }

        }

        private void showEditDistances()
        {
            EditListViewDistances editDistances = new EditListViewDistances(listViewDistances);
            editDistances.ShowDialog();
            this.Focus();
        }

        private void listViewDistances_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            showEditDistances();
        }

        private void listViewDistances_MouseClick(object sender, MouseEventArgs e)
        {
            showEditDistances();
        }

        private void showEditModalities()
        {
            EditListViewModalities editModalities = new EditListViewModalities(listViewModalities);
            editModalities.ShowDialog();
            this.Focus();
        }

        private void listViewModalities_MouseClick(object sender, MouseEventArgs e)
        {
            showEditModalities();
        }

        private void listViewModalities_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            showEditModalities();
        }

        private void showEditRoutes()
        {
            EditListViewRoutes editRoutes = new EditListViewRoutes(listViewRouteCodes);
            editRoutes.ShowDialog();
            this.Focus();
        }

        private void listViewRouteCodes_MouseClick(object sender, MouseEventArgs e)
        {
            showEditRoutes();
        }

        private void listViewRouteCodes_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            showEditRoutes();
        }

        private void showEditContainers()
        {
            EditListViewContainers editContainers = new EditListViewContainers(listViewContainers);
            editContainers.ShowDialog();
            this.Focus();
        }

        private void listViewContainers_MouseClick(object sender, MouseEventArgs e)
        {
            showEditContainers();
        }

        private void listViewContainers_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            showEditContainers();
        }

        private void showEditClasses(string classNumber)
        {
            ListView actListView;

            switch (classNumber)
            {
                case "I" :
                    actListView = listViewCategoryI;
                    break;
                case "II":
                    actListView = listViewCategoryII;
                    break;
                case "III":
                    actListView = listViewCategoryIII;
                    break;
                case "IIIB":
                    actListView = listViewCategoryIIIB;
                    break;
                default :
                    throw new Exception("Nem megfelelő kategória jel!");
            }

            EditListViewClasses editClasses = new EditListViewClasses(actListView, classNumber);
            editClasses.ShowDialog();
            this.Focus();
        }

        private void listViewCategory_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            showEditClasses(((ListView)sender).Tag.ToString());
        }

        private void listViewCategory_MouseClick(object sender, MouseEventArgs e)
        {
            showEditClasses(((ListView)sender).Tag.ToString());
        }

        private bool validateWinterWeekly()
        {
            return Utils.validateMustHaveDigitsOnly(errorProvider, textBoxWinterWeekly, false, ErrorIconAlignment.MiddleLeft);
        }

        private void textBoxWinterWeekly_Validating(object sender, CancelEventArgs e)
        {
            validateWinterWeekly();
        }

        private bool validateSummerWeekly()
        {
            return Utils.validateMustHaveDigitsOnly(errorProvider, textBoxSummerWeekly, false, ErrorIconAlignment.MiddleLeft); ;
        }

        private void textBoxSummerWeekly_Validating(object sender, CancelEventArgs e)
        {
            validateSummerWeekly();
        }

        private bool validateDepotName()
        {
            return Utils.validateMustNonEmpty(errorProvider, textBoxDepotName);
        }

        private void textBoxDepotName_Validating(object sender, CancelEventArgs e)
        {
            validateDepotName();
        }

        
    }

    
}
