using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace AdvertsingProfitControl
{
    public partial class FrmMain : Form
    {
        private double _SalesProducedByAdItems = 0;
        private double _TotalProfitReturnFromAdItems = 0;
        private double _gCostOfSalesCalculatedTotal = 0;
        private double _departmentSales = 0;
        private List<string> _gDateStringCollection = new List<string>();
        readonly FrmLogConsole _console = FrmLogConsole.GetStaticInstance;
        private int _LazyPageCounter = 0;

        public FrmMain()
        {
            InitializeComponent();

            //Set the maximum and minimum sizes for the form.
            //MaximumSize = new Size(1200, 650);
            //MinimumSize = new Size(1000, 550);
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            var versionControl = new DatabaseVersionControl();
            var version = versionControl.GetDatabaseVerionNumber(databaseTracker.DatabaseConnectionString);
            if(version == "0.3.0.0")
            {
                MessageBox.Show("An older version of the APC database has been detected.\nAdvertising Profit Control " + Application.ProductVersion + " will now attempt to update it.", "Outdated Database Detected");
                string versionNumber = "";
                if (versionControl.UpdateVersionPointFive(databaseTracker.DatabaseConnectionString, out versionNumber))
                {
                    MessageBox.Show("The database has been successfully upgraded to version " + versionNumber + ".\nA back up of the old database has been made called APCDatabase.bak in the same location as the current database.", "Half Baked Code For The Win");
                }
            }
            RowParsing.AdSpecialGroups.AddRange(databaseReader.ReturnGroupNameList(databaseTracker.DatabaseConnectionString));
            FillDateSuggestionComboBoxes();
            BuildAndFillDataGridTables();
            CalculateProfitAnalysis();
            CalculateGrossProfit();
            projectedSalesMainDataGrid.KeyDown += FrmMain_KeyDown;
            //var margin = new Margins(50, 50, 0, 0);
            //_printDoc.DefaultPageSettings.Margins = margin;
        }

        private void FrmMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Shift && e.KeyCode == Keys.Up)
            {
                MessageBox.Show("My message");
            }
        }

        private void UpdateDataGridViewInformation(object sender, EventArgs e)
        {
            var dateString = monthComboBox.Text + "/" + dayComboBox.Text + "/" + yearComboBox.Text;
            BuildAndFillDataGridTables(dateString);
            CalculateProfitAnalysis();
            CalculateGrossProfit();
        }

        /// <summary>
        /// Builds and fills the DataGridView tables on the main form 
        /// from the either the most recent date or the date specified in the parameter.
        /// </summary>
        /// <param name="dateString">The date of records to display to the user, if no date is specified then the most recent date is used.</param>
        private void BuildAndFillDataGridTables(string dateString = "")
        {
            //
            var databaseTracker = new DatabaseTracker();
            var dataBaseReader = new DatabaseReader();
            //
            var dateId = "";

            //Check to see if a parameter has been passed.
            if (dateString == "")
            {
                //IF non were, then grab the most recent date ID from the database and use that.
                dateId = dataBaseReader.RetrieveMostRecentDateId(databaseTracker.DatabaseConnectionString);
                _console.WriteToLog(FrmLogConsole.Level.Info,  dateId != "0" ? "Most recent date ID is " + dateId : "Most recent date ID is unavailable.");
            }
            else
            {
                //ELSE IF one was passed, then use it's ID to build the tables.
                dateId = dataBaseReader.RetrieveDateIdByDateString(dateString, databaseTracker.DatabaseConnectionString);
                _console.WriteToLog(FrmLogConsole.Level.Info, dateId != "0" ? "Date ID for " + dateString + " is resolved to have the ID of " + dateId + "." : "The date " + dateString + " could not be found in the database.");
                if (dateId == "0")
                {
                    _gDateStringCollection.Remove(dateString);
                }
            }
            //Now check to make sure there were no errors grabbing the ID, IF there were return.
            if (dateId == "0") return;
            //Clear the class global variables to prevents calculation mishaps.
            _SalesProducedByAdItems = 0;
            _TotalProfitReturnFromAdItems = 0;
            _gCostOfSalesCalculatedTotal = 0;
            //Clear all DataGridViews since the date supplied is valid and in the database.
            projectedSalesMainDataGrid.DataSource = null;
            projectedSalesMainDataGrid.Columns.Clear();
            inventoryDataGridView.DataSource = null;
            inventoryDataGridView.Columns.Clear();
            actualSalesMainDataGidView.DataSource = null;
            actualSalesMainDataGidView.Columns.Clear();
            suppliersDataGridView.DataSource = null;
            weeklySalesDataGridView.DataSource = null;
            //Begin by grabbing the Projections table
            var tempTable = dataBaseReader.ReturnProjectionsTable(dateId, databaseTracker.DatabaseConnectionString);
            if (tempTable.Rows.Count > 0)
            {
                BuildSalesDataGridViews(projectedSalesMainDataGrid, tempTable);
            }

            //Grabbing the Inventory table
            tempTable = dataBaseReader.ReturnInventoryTable(dateId, databaseTracker.DatabaseConnectionString);
            if (tempTable.Rows.Count > 0)
            {
                BuildInventoryDataGridView(inventoryDataGridView, tempTable);
            }

            //And the Actual Sales table
            tempTable = dataBaseReader.ReturnActualSales(dateId, databaseTracker.DatabaseConnectionString);
            if (tempTable.Rows.Count > 0)
            {
                BuildSalesDataGridViews(actualSalesMainDataGidView, tempTable);
            }

            //Next the Invoices table
            tempTable = dataBaseReader.ReturnInvoiceTable(dateId, databaseTracker.DatabaseConnectionString);
            if (tempTable.Rows.Count > 0)
            {
                suppliersDataGridView.DataSource = SumCostOfSales(tempTable);
            }

            //And finally the weekly sales
            tempTable = dataBaseReader.ReturnWeeklySalesFromDateId(dateId, databaseTracker.DatabaseConnectionString);
            if (tempTable.Rows.Count > 0)
            {
                weeklySalesDataGridView.DataSource = tempTable;
            }

            commentsTextBox.Text = dataBaseReader.RetrieveComments(dateId, databaseTracker.DatabaseConnectionString);
        }

        private void CalculateProfitAnalysis(double shrink = 0.30)
        {
            if (Math.Abs(_SalesProducedByAdItems) < 1 || Math.Abs(_TotalProfitReturnFromAdItems) < 1)
            {
                //Clear the labels...
                if (weeklySalesDataGridView.Rows.Count == 0 || weeklySalesDataGridView.Rows[0].Cells[7].EditedFormattedValue.ToString() == "0.0000")
                {
                    departmentSalesLabel.Text = "Department Sales: No Weekly Sales Found.";
                    departmentSalesLabel.ForeColor = Color.Red;
                }

                if (_SalesProducedByAdItems == 0)
                {
                    salesProducedLabel.Text = "Sales Produced By Ad Items (A): No Values to Total.";
                    salesProducedLabel.ForeColor = Color.Red;
                }

                remainingSalesLabel.Text = "Remaining Sales: ";
                if (_TotalProfitReturnFromAdItems == 0)
                {
                    totalProfitFromAdItemsLabel.Text = "Total Profit Return From Ad Items (B): No Values to Total.";
                    totalProfitFromAdItemsLabel.ForeColor = Color.Red;
                }

                totalProfitReturnFromRemaingLabel.Text = "Total Profit Return From Remaining Sales: ";
                totalProfitReturnLabel.Text = "Total Profit Return: ";
                return;
            }
            double.TryParse(weeklySalesDataGridView.Rows[0].Cells[7].EditedFormattedValue.ToString(), out _departmentSales);
            //Since there are department sales, change the label's color to make sure it doesn't appear as an error.
            departmentSalesLabel.ForeColor = Color.Black;
            departmentSalesLabel.Text = "Department Sales: " + _departmentSales.ToString("C");
            //Assume that the sales produced is larger then zero (0).
            salesProducedLabel.ForeColor = Color.Black;
            salesProducedLabel.Text = "Sales Produced By Ad Items (A): " + _SalesProducedByAdItems.ToString("C");

            double remainingSales = _departmentSales - _SalesProducedByAdItems;
            remainingSalesLabel.Text = "Remaining Sales: " + remainingSales.ToString("C");
            //Again assume the total profit return is larger then zero (0).
            totalProfitFromAdItemsLabel.ForeColor = Color.Black;
            totalProfitFromAdItemsLabel.Text = "Total Profit Return From Ad Items (B): " + _TotalProfitReturnFromAdItems.ToString("C");
            //Shrink is being used as a place holder for Cross Profit % which is obtained by dividing gActualTotalProfitReturnCalculatedTotal by the department weekly retail sales.
            double totalProfitReturnFromRemainingSales = shrink * remainingSales;
            //
            totalProfitReturnFromRemaingLabel.Text = "Total Profit Return From Remaining Sales: " + totalProfitReturnFromRemainingSales.ToString("C");
            double totalProfitReturn = _TotalProfitReturnFromAdItems + totalProfitReturnFromRemainingSales;
            totalProfitReturnLabel.Text = "Total Profit Return: " + totalProfitReturn.ToString("C");
        }

        private void BuildSalesDataGridViews(DataGridView dataGridView, DataTable table)
        {
            var adSpecialIndex = -1;
            double totalSales = 0;
            double totalProfitReturn = 0;

            foreach (DataColumn column in table.Columns)
            {
                var dataGridViewColumn = new DataGridViewColumn()
                {
                    HeaderText = column.ColumnName,
                    CellTemplate = new DataGridViewTextBoxCell()
                };
                if (dataGridViewColumn.HeaderText.Contains("Projection"))
                {
                    dataGridViewColumn.HeaderText = dataGridViewColumn.HeaderText.Replace("Projection", "");
                }
                else if (dataGridViewColumn.HeaderText.Contains("Actual"))
                {
                    dataGridViewColumn.HeaderText = dataGridViewColumn.HeaderText.Replace("Actual", "");
                }
                if (dataGridViewColumn.HeaderText == "FK_GroupID" || dataGridViewColumn.HeaderText == "RowAttribute")
                {
                    dataGridViewColumn.Visible = false;
                }
                dataGridViewColumn.HeaderText = TextFormat.AddSpacesToSentence(dataGridViewColumn.HeaderText, false);
                dataGridView.Columns.Add(dataGridViewColumn);
            }

            for (var i = 0; i < table.Rows.Count; i++)
            {
                var row = new DataGridViewRow();
                //Checks for the group, if any, the row or rows is/are part of.
                if (table.Rows[i][8].ToString() != "" &&
                    int.Parse(table.Rows[i][8].ToString()) != 0 && adSpecialIndex == -1)
                {
                    adSpecialIndex = i;
                    var adSpecialRow = new DataGridViewRow();
                    var databaseTracker = new DatabaseTracker();
                    var databaseReader = new DatabaseReader();
                    var groupName = databaseReader.ReturnGroupNameFromGroupId(table.Rows[i][8].ToString(), databaseTracker.DatabaseConnectionString);

                    adSpecialRow.DefaultCellStyle.BackColor = Color.DarkGray;

                    dataGridView.Rows.Add(adSpecialRow);
                    dataGridView.Rows[i].Cells[0].Value = groupName;
                }
                //Checks for row attribute
                if (table.Rows[i][7].ToString() != "")
                {
                    //The seventh column contains the row's attribute if any.
                    var rowAttribute = int.Parse(table.Rows[i][7].ToString());
                    if (rowAttribute == 1)
                    {
                        row.DefaultCellStyle.BackColor = Color.LightGray;
                    }
                    else if (rowAttribute == 2)
                    {
                        row.DefaultCellStyle.BackColor = Color.LightBlue;
                    }

                    foreach (var dataCell in table.Rows[i].ItemArray.Select(cell => new DataGridViewTextBoxCell { Value = cell }))
                    {
                        row.Cells.Add(dataCell);
                    }
                    dataGridView.Rows.Add(row);
                }
                else
                {
                    dataGridView.Rows.Add(table.Rows[i].ItemArray);
                }
                //Check for values in the Total Sales and Total Profit Return columns
                double tempOut = 0;
                if (double.TryParse(table.Rows[i][3].ToString(), out tempOut))
                {
                    if (tempOut >= 0)
                    {
                        totalSales += tempOut;
                    }
                }
                if (double.TryParse(table.Rows[i][6].ToString(), out tempOut))
                {
                    if (tempOut >= 0)
                    {
                        totalProfitReturn += tempOut;
                    }
                }
            }
            var totalsRow = new object[9];
            totalsRow[0] = "Totals";
            totalsRow[3] = totalSales;
            totalsRow[6] = totalProfitReturn;
            dataGridView.Rows.Add(totalsRow);

            if (dataGridView.Name == "actualSalesMainDataGidView")
            {
                _SalesProducedByAdItems = totalSales;
                _TotalProfitReturnFromAdItems = totalProfitReturn;
            }
        }

        private void BuildInventoryDataGridView(DataGridView dataGridView, DataTable table)
        {
            var lastAdSpecialIndex = -1;
            for (var columnIndex = 0; columnIndex < table.Columns.Count; columnIndex++)
            {
                var dataGridViewColumn = new DataGridViewColumn
                {
                    Name = table.Columns[columnIndex].ColumnName,
                    CellTemplate = new DataGridViewTextBoxCell()
                };
                var columnHeaderText = table.Columns[columnIndex].ColumnName;
                columnHeaderText = TextFormat.AddSpacesToSentence(columnHeaderText, false);
                //Make the row attribute column invisible.
                if (table.Columns[columnIndex].ColumnName == "RowAttribute")
                {
                    dataGridViewColumn.Visible = false;
                }
                //Make any columns with a foreign key invisible.
                if (table.Columns[columnIndex].ColumnName.Contains("FK"))
                {
                    dataGridViewColumn.Visible = false;
                }
                dataGridViewColumn.HeaderText = columnHeaderText;
                dataGridView.Columns.Add(dataGridViewColumn);
            }

            for (var rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++)
            {
                var row = new DataGridViewRow();

                if (table.Rows[rowIndex][6].ToString() != "" && int.Parse(table.Rows[rowIndex][6].ToString()) != 0 && lastAdSpecialIndex == -1)
                {
                    lastAdSpecialIndex = rowIndex;
                    var adSpecialRow = new DataGridViewRow();
                    var databaseTracker = new DatabaseTracker();
                    var databaseReader = new DatabaseReader();
                    var groupName = databaseReader.ReturnGroupNameFromGroupId(table.Rows[rowIndex][6].ToString(), databaseTracker.DatabaseConnectionString);

                    adSpecialRow.DefaultCellStyle.BackColor = Color.DarkGray;

                    dataGridView.Rows.Add(adSpecialRow);
                    dataGridView.Rows[rowIndex].Cells[0].Value = groupName;
                }

                if (table.Rows[rowIndex][5].ToString() != "")
                {
                    //The fifth column contains the row's attribute if any.
                    var rowAttribute = int.Parse(table.Rows[rowIndex][5].ToString());
                    if (rowAttribute == 1)
                    {
                        row.DefaultCellStyle.BackColor = Color.LightGray;
                    }
                    else if (rowAttribute == 2)
                    {
                        row.DefaultCellStyle.BackColor = Color.LightBlue;
                    }

                    foreach (var dataCell in table.Rows[rowIndex].ItemArray.Select(cell => new DataGridViewTextBoxCell { Value = cell }))
                    {
                        row.Cells.Add(dataCell);
                    }
                    dataGridView.Rows.Add(row);
                }
                else
                {
                    dataGridView.Rows.Add(table.Rows[rowIndex].ItemArray);
                }
            }
        }

        private void CalculateGrossProfit()
        {
            if (Math.Abs(_gCostOfSalesCalculatedTotal) < 1)
            {
                //IF Cost of Sales hasn't been calculated, then clear labels and return.
                if (weeklySalesDataGridView.Rows.Count == 0 || weeklySalesDataGridView.Rows[0].Cells[7].EditedFormattedValue.ToString() == "0.0000")
                {
                    grossProfitTotalSales.Text = "Total Sales: No Weekly Sales Found.";
                    grossProfitTotalSales.ForeColor = Color.Red;
                }
                grossProfitLessCostOfSales.Text = "Less Cost of Sales: ";
                grossProfitDollarGrossProfitLabel.Text = "Dollar Gross Profit: ";
                perfectGrossProfitLabel.Text = "Percent Gross Profit: ";
                return;
            }

            double totalSales = Convert.ToDouble(weeklySalesDataGridView.Rows[0].Cells[7].EditedFormattedValue.ToString());
            grossProfitTotalSales.ForeColor = Color.Black;
            grossProfitTotalSales.Text = "Total Sales: " + totalSales.ToString("C");
            grossProfitLessCostOfSales.Text = "Less Cost of Sales: " + _gCostOfSalesCalculatedTotal.ToString("C");
            double dollarGrossProfit = totalSales - _gCostOfSalesCalculatedTotal;
            grossProfitDollarGrossProfitLabel.Text = "Dollar Gross Profit: " + dollarGrossProfit.ToString("C");
            double grossProfitPercent = dollarGrossProfit / totalSales;
            perfectGrossProfitLabel.Text = "Percent Gross Profit: " + grossProfitPercent.ToString("P");
        }

        private void addRecordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var recordForm = new FrmAddRecord();
            recordForm.ShowDialog();
            FillDateSuggestionComboBoxes();
            BuildAndFillDataGridTables();
            CalculateProfitAnalysis();
            CalculateGrossProfit();
        }

        /// <summary>
        /// Appends a new "Totals" row to the end of the Invoice table that is passed in
        /// and sums up the Net Cost of Invoices column as well as storing the total Costs of Sales
        /// into the class wide variable for use with other functions.
        /// </summary>
        /// <param name="invoiceTable">The Invoice table to summed.</param>
        /// <returns></returns>
        private DataTable SumCostOfSales(DataTable invoiceTable)
        {
            //Check for a null parameter OR if the column count is less then six (6) as any less means the database isn't returning correctly.
            if(invoiceTable == null || invoiceTable.Columns.Count < 6) return invoiceTable;
            double costOfSalesSum = 0;

            for (var i = 0; i < invoiceTable.Rows.Count; i++)
            {
                costOfSalesSum += Convert.ToDouble(invoiceTable.Rows[i][4]);
            }

            _gCostOfSalesCalculatedTotal = costOfSalesSum;

            object[] invoiceTotalRow = new object[invoiceTable.Columns.Count];
            invoiceTotalRow[0] = "Total Purchases";
            invoiceTotalRow[4] = costOfSalesSum;
            invoiceTable.Rows.Add(invoiceTotalRow);

            return invoiceTable;
        }

        private void showHideConsoleHelpMainMenu_Click(object sender, EventArgs e)
        {
            if (_console.IsVisable)
            {
                _console.Hide();
            }
            else
            {
                _console.Show();
            }
 
        }

        /// <summary>
        /// Grabs all dates from the database and splits the returned strings 
        /// into months, days, and years and stores them in their respective 
        /// combo boxes to display to the user. Also stores the list of dates
        /// inside a class wide variable.
        /// </summary>
        private void FillDateSuggestionComboBoxes()
        {
            //Create a connection to the database retrieval class.
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            //Grab the most recent date in the database.
            var mostRecentDateTime = databaseReader.RetrieveMostRecentDateString(databaseTracker.DatabaseConnectionString);
            var mostRecentDateString = mostRecentDateTime.ToString("MM/dd/yyyy");
            //Check to see if the return value is null and IF so log the error and return.
            if(mostRecentDateString == ""){ _console.WriteToLog(FrmLogConsole.Level.Error, "No dates could be found in the database."); return;}
            //Otherwise, if there was a return date, split it into a array.
            var mostRecentDateParts = mostRecentDateString.Split('/');
            //Grab only the most recent years in the database (only say 2015) and fill a table with the dates. Indexes are as follows: [0] is Month, [1] is Day and [2] is Year.
            var datesList = databaseReader.RetrieveDateListByYear(mostRecentDateParts[2], databaseTracker.DatabaseConnectionString);
            //Suspend the control's drawing so the user doesn't see any ugly enumeration and index changing.
            DrawingControl.SuspendDrawing(dateSelectorPanel);
            //Considering there was a return value for the most recent date, its safe to assume there is at least one date in the database, so clear the class's date collection.
            _gDateStringCollection.Clear();
            monthComboBox.Items.Clear();
            dayComboBox.Items.Clear();
            yearComboBox.Items.Clear();
            monthComboBox.SelectedIndexChanged -= UpdateDaysOfMonth;
            dayComboBox.SelectedIndexChanged -= UpdateDataGridViewInformation;
            yearComboBox.SelectedIndexChanged -= UpdateDaysOfMonthByYear;
            //Now spin through the oneYearDatesTable and fill the class wide object with all the dates for the most recent year.
            for (var i = 0; i < datesList.Count; i ++)
            {
                var fullDateString = datesList[i].ToString("MM/dd/yyyy");
                //Check for nulls just to be paranoid.
                if (fullDateString == "")
                {
                    return;
                }
                //IF the date string collection already contains the date, then continue to the next iteration.
                if (_gDateStringCollection.Contains(fullDateString))
                {
                    continue;
                }
                _gDateStringCollection.Add(fullDateString);
            }

            var dayBasedOnMonthAndYeaRegex = new Regex("^0?" + mostRecentDateParts[0] + @"/\d{2}/" + mostRecentDateParts[2]);
            var monthBasedOnYearRegex = new Regex(@"^\d{2}/\d{2}/" + mostRecentDateParts[2]);
            for (var i = 0; i < _gDateStringCollection.Count; i++)
            {
                string[] dateArray = _gDateStringCollection[i].Split('/');
                var month = dateArray[0];
                var day =dateArray[1];

                if (dayBasedOnMonthAndYeaRegex.IsMatch(_gDateStringCollection[i]))
                {
                    dayComboBox.Items.Add(day);
                }
                if (monthBasedOnYearRegex.IsMatch(_gDateStringCollection[i]))
                {
                    if (!monthComboBox.Items.Contains(month))
                    {
                        monthComboBox.Items.Add(month);
                    }
                }
            }

            var yearsInDatabase = databaseReader.RetrieveUniqueYearsList(databaseTracker.DatabaseConnectionString);

            foreach (var year in yearsInDatabase)
            {
                yearComboBox.Items.Add(year);
            }

            if (dayComboBox.Items.Count >= 1 && yearComboBox.Items.Count >= 1 && monthComboBox.Items.Count >= 1)
            {
                monthComboBox.SelectedIndex = monthComboBox.Items.Count - 1;
                dayComboBox.SelectedIndex = dayComboBox.Items.Count - 1;
                yearComboBox.SelectedIndex = yearComboBox.Items.Count - 1;
                monthComboBox.Enabled = true;
                dayComboBox.Enabled = true;
                yearComboBox.Enabled = true;
            }
            else
            {
                monthComboBox.Enabled = false;
                dayComboBox.Enabled = false;
                yearComboBox.Enabled = false;
            }
            monthComboBox.SelectedIndexChanged += UpdateDaysOfMonth;
            dayComboBox.SelectedIndexChanged += UpdateDataGridViewInformation;
            yearComboBox.SelectedIndexChanged += UpdateDaysOfMonthByYear;
            DrawingControl.ResumeDrawing(dateSelectorPanel);
        }

        private void UpdateDaysOfMonth(object sender, EventArgs e)
        {
            if (yearComboBox.SelectedIndex == -1) return; 
            var year = yearComboBox.SelectedItem.ToString();
            var month = monthComboBox.SelectedItem.ToString();
            var dateParserPattern = new Regex("^" + month + @"\/\d{2}\/" + year);

            dayComboBox.Items.Clear();

            for (var i = 0; i < _gDateStringCollection.Count; i++)
            {
                if (dateParserPattern.IsMatch(_gDateStringCollection[i]))
                {
                    var dateArray = _gDateStringCollection[i].Split('/');
                    var day = dateArray[1];
                    dayComboBox.Items.Add(day);
                }
            }

            if (dayComboBox.Items.Count > 0)
            {
                dayComboBox.SelectedIndex = dayComboBox.Items.Count - 1;
            }

            CalculateProfitAnalysis();
            CalculateGrossProfit();
        }
        /// <summary>
        /// Fires when the Year combo box's index changes.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateDaysOfMonthByYear(object sender, EventArgs e)
        {
            //Obligatory database retrieval call...
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            //First, grab the year and the month from their respective combo boxes.
            var year = yearComboBox.SelectedItem.ToString();
            var month = monthComboBox.SelectedItem.ToString();
            //Since we can more or less be certain that nothing is null, clear the current date collection.
            _gDateStringCollection.Clear();
            var months = databaseReader.RetrieveUniqueMonthsList(year, databaseTracker.DatabaseConnectionString);
            var mostRecentMonth = months.Max();
            if (mostRecentMonth.Length == 1)
            {
                mostRecentMonth = "0" + mostRecentMonth;
            }
            var datesList = databaseReader.RetrieveDateListByYear(year, databaseTracker.DatabaseConnectionString);
  
            for (var i = 0; i < datesList.Count; i++)
            {
                _gDateStringCollection.Add(datesList[i].ToString("MM/dd/yyyy"));
            }

            //Clear the month and day combo boxes and unregister their event handlers.
            dayComboBox.Items.Clear();
            monthComboBox.Items.Clear();
            monthComboBox.SelectedIndexChanged -= UpdateDaysOfMonth;
            dayComboBox.SelectedIndexChanged -= UpdateDataGridViewInformation;
            for (var i = 0; i < _gDateStringCollection.Count; i ++)
            {
                var dateArray = _gDateStringCollection[i].Split('/');
                month = dateArray[0];
                //Declare the patterns to look for when enumerating the combo boxes.
                var dayBasedOnMonthAndYeaRegex = new Regex(@"^(" + mostRecentMonth + @"\/\d{2}\/" + year + ")"); //Only allows days that are actually part of the month and year.
                var day = dateArray[1];

                if (dayBasedOnMonthAndYeaRegex.IsMatch(_gDateStringCollection[i]))
                {
                    dayComboBox.Items.Add(day);
                }

                if (!monthComboBox.Items.Contains(month))
                {
                    monthComboBox.Items.Add(month);   
                }
            }

            if (dayComboBox.Items.Count > 0)
            {
                dayComboBox.SelectedIndex = dayComboBox.Items.Count - 1;
            }
            if (monthComboBox.Items.Count > 0)
            {
                monthComboBox.SelectedIndex = monthComboBox.Items.Count - 1;
            }

            //Now re-register the event handlers
            monthComboBox.SelectedIndexChanged += UpdateDaysOfMonth;
            dayComboBox.SelectedIndexChanged += UpdateDataGridViewInformation;

            BuildAndFillDataGridTables(monthComboBox.SelectedItem + "/" + dayComboBox.SelectedItem + "/" + year);
            CalculateProfitAnalysis();
            CalculateGrossProfit();
        }

        private void adSpecialKeyWordsToolsMainMenu_Click(object sender, EventArgs e)
        {
            var keyWordRegister = new FrmAdSpecialRegister();
            keyWordRegister.ShowDialog();
        }

        private void deleteRecordsMainMenu_Click(object sender, EventArgs e)
        {
            var frmDeleteRecord = new FrmDeleteRecord();
            frmDeleteRecord.ShowDialog();
            FillDateSuggestionComboBoxes();
            BuildAndFillDataGridTables();
            CalculateProfitAnalysis();
            CalculateGrossProfit();
        }

        private void modifyRecordMainMenu_Click(object sender, EventArgs e)
        {
            var modifyForm = new FrmModifyRecord();
            modifyForm.ShowDialog();
            BuildAndFillDataGridTables();
            CalculateProfitAnalysis();
            CalculateGrossProfit();
        }

        private void manageItemsToolsMainMenu_Click(object sender, EventArgs e)
        {
            var adItemManager = new FrmManageAdItems();
            adItemManager.ShowDialog();
        }

        private void dbVersionHelpMainMenu_Click(object sender, EventArgs e)
        {
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            var version = databaseReader.GetDatabaseVersion(databaseTracker.DatabaseConnectionString);

            if (version != "0.0.0.0")
            {
                MessageBox.Show("The current database's version is " + version + ".", "Database Version Number");
            }
        }

        private void PrintPage(object sender, PrintPageEventArgs e)
        {
            Bitmap bitMap;
            if (_LazyPageCounter == 0)
            {
                bitMap = new Bitmap(Application.StartupPath + "\\FrontPage.png");
            }
            else
            {
                bitMap = new Bitmap(Application.StartupPath + "\\BackPage.png");
            }

            var rect = e.MarginBounds;

            if ((double)bitMap.Width / (double)bitMap.Height > (double)rect.Width / (double)rect.Height) // image is wider
            {
                rect.Height = (int)((double)bitMap.Height / (double)bitMap.Width * (double)rect.Width);
            }
            else
            {
                rect.Width = (int)((double)bitMap.Width / (double)bitMap.Height * (double)rect.Height);
            }

            if (_LazyPageCounter == 0)
            {
                e.Graphics.DrawImage(bitMap, new Rectangle(0, 25, 850, 1050));
                _LazyPageCounter++;
                e.HasMorePages = true;
            }
            else
            {
                e.Graphics.DrawImage(bitMap, new Rectangle(0, 0, 850, 1100));
                _LazyPageCounter = 0;
                e.HasMorePages = false;
            }
        }

        private void DisplayPrintPreview(object sender, EventArgs e)
        {
            //Build and render the front and back forms of the document.
            var test = new FrontPageGenerator();
            var backPageTest = new BackPageGenerator();
            var printTestPage = new PrintDocument();
            var printDialog = new PrintPreviewDialog();
            if (!usePreRenderedFilesCheckbox.Checked)
            {
                var databaseTracker = new DatabaseTracker();
                var databaseReader = new DatabaseReader();
                var dateId =
                    databaseReader.RetrieveDateIdByDateString(
                        monthComboBox.SelectedItem + "/" + dayComboBox.SelectedItem + "/" + yearComboBox.SelectedItem,
                        databaseTracker.DatabaseConnectionString);
                double remaingingSales = _departmentSales - _SalesProducedByAdItems;
                double totalProfitReturnFromReminaingSales = remaingingSales*.3;
                double totalProfitReturn = _TotalProfitReturnFromAdItems + totalProfitReturnFromReminaingSales;
                test.BuildFormFrontCompressedLayout(dateId, _departmentSales, _SalesProducedByAdItems, remaingingSales,
                    _TotalProfitReturnFromAdItems, totalProfitReturnFromReminaingSales, totalProfitReturn,
                    commentsTextBox.Text);
                test.RenderHtmlToImage();
                backPageTest.GenerateWeeklyInventoryControlPage(dateId);
                backPageTest.RenderHtmlToImage();
            }
            else
            {
                if (File.Exists(Application.StartupPath + "\\" + "FrontPage.html") &&
                    File.Exists(Application.StartupPath + "\\" + "Backpage.html"))
                {
                    test.RenderHtmlToImage();
                    backPageTest.RenderHtmlToImage();
                }
            }

            //var margin = new Margins(50, 50, 0, 0);
            //printDoc.DefaultPageSettings.Margins = margin;
            printTestPage.PrintPage += PrintPage;
            printDialog.Document = printTestPage;
            printDialog.ShowDialog();
            printDialog.Document = new PrintDocument();
        }

        private void newFormTestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var form = new NewAddRecord();
            form.ShowDialog();

        }
    }

    //http://stackoverflow.com/questions/487661/how-do-i-suspend-painting-for-a-control-and-its-children
    internal class DrawingControl
    {
        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);

        private const int WM_SETREDRAW = 11;

        public static void SuspendDrawing(Control parent)
        {
            SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
        }

        public static void ResumeDrawing(Control parent)
        {
            SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
            parent.Refresh();
        }
    }
}
