using System;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace AdvertsingProfitControl
{
    public partial class FrmMain : Form
    {
        private double _salesProducedByAdItems;
        private double _totalProfitReturnFromAdItems;
        private double _totalInvoicePurchases; //Total Purchases
        private double _departmentSales; //weekly sales total
        private DateTime _currentActiveDate;
        private readonly FrmLogConsole _console = FrmLogConsole.GetStaticInstance;
        private int _LazyPageCounter;

        public FrmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            monthCalendar.BoldedDates = databaseReader.RetrieveDates(databaseTracker.DatabaseConnectionString).ToArray();
            ConstructApcDataGridViews();
            ConstructInvoicesDataGridView();
            RowParsing.AdSpecialGroups.AddRange(databaseReader.ReturnGroupNameList(databaseTracker.DatabaseConnectionString));
            var date = databaseReader.RetrieveMostRecentDate(databaseTracker.DatabaseConnectionString);
            _currentActiveDate = date;
            LoadDate(date);
            monthCalendar.DateChanged += ValidateDateChanged;
            //projectionsDataGridView.KeyDown += FrmMain_KeyDown;
            //var margin = new Margins(50, 50, 0, 0);
            //_printDoc.DefaultPageSettings.Margins = margin;
        }

        private void CalculateProfitAnalysis(double shrink = 0.30)
        {
            if (actualSalesDataGridView.Rows.Count == 0)
            {
                salesProducedLabel.Text = @"Sales Produced By Ad Items (A): No Data";
                totalProfitFromAdItemsLabel.Text = @"Total Profit Return " + Environment.NewLine + @" From Ad Items (B): No Data";
                if (Math.Abs(_departmentSales) < 1)
                {
                    departmentSalesLabel.Text = @"Department Sales: No Data";
                }
                return;
            }
            var incompleteData = false;
            //First grab the total sales and the total profit return generated by the actual sales of product.
            if (
                double.TryParse(
                    actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[3].EditedFormattedValue
                        .ToString(), out _salesProducedByAdItems))
            {
                //The sales parsed properly so there is data in the cell. Next try to grab the total profit return.
                if (double.TryParse(
                    actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[6].EditedFormattedValue
                        .ToString(), out _totalProfitReturnFromAdItems))
                {
                    
                }
            }
            if (Math.Abs(_salesProducedByAdItems) < 1)
            {
                salesProducedLabel.Text = @"Sales Produced By Ad Items (A): No Data";
                incompleteData = true;
            }
            if (Math.Abs(_totalProfitReturnFromAdItems) < 1)
            {
                totalProfitFromAdItemsLabel.Text = @"Total Profit Return " + Environment.NewLine + @"From Ad Items (B): No Data";
                incompleteData = true;
            }
            if (Math.Abs(_departmentSales) < 1)
            {
                departmentSalesLabel.Text = @"Department Sales: No Data";
                incompleteData = true;
            }
            if (incompleteData)
            {
                return;
            }
            departmentSalesLabel.Text = @"Department Sales: " + _departmentSales.ToString("C");
            salesProducedLabel.Text = @"Sales Produced By Ad Items (A): " + _salesProducedByAdItems.ToString("C");
            //Calculate the remaining sales.
            var remainingSales = _departmentSales - _salesProducedByAdItems;
            remainingSalesLabel.Text = @"Remaining Sales: " + remainingSales.ToString("C");
            //Again assume the total profit return is larger then zero (0).
            totalProfitFromAdItemsLabel.Text = @"Total Profit Return" + Environment.NewLine + @" From Ad Items (B): " + _totalProfitReturnFromAdItems.ToString("C");
            //Shrink is being used as a place holder for Cross Profit % which is obtained by dividing the total profit return from the department weekly retail sales.
            var totalProfitReturnFromRemainingSales = shrink*remainingSales;
            //
            totalProfitReturnFromRemaingLabel.Text = @"Total Profit Return" + Environment.NewLine + @" From Remaining Sales: " + totalProfitReturnFromRemainingSales.ToString("C");
            var totalProfitReturn = _totalProfitReturnFromAdItems + totalProfitReturnFromRemainingSales;
            totalProfitReturnLabel.Text = @"Total Profit Return: " + totalProfitReturn.ToString("C");
        }

        private void CalculateGrossProfit()
        {
            if (Math.Abs(_totalInvoicePurchases) < 1)
            {
                //IF Cost of Sales hasn't been calculated, then clear labels and return.
                if (Math.Abs(_departmentSales) < 1)
                {
                    grossProfitTotalSales.Text = @"Total Sales: No Data";
                }
                grossProfitLessCostOfSales.Text = @"Less Cost of Sales: No Data";
                return;
            }
            grossProfitTotalSales.Text = @"Total Sales: " + _departmentSales.ToString("C");
            grossProfitLessCostOfSales.Text = @"Less Cost of Sales: " + _totalInvoicePurchases.ToString("C");
            var dollarGrossProfit = _departmentSales - _totalInvoicePurchases;
            grossProfitDollarGrossProfitLabel.Text = @"Dollar Gross Profit: " + dollarGrossProfit.ToString("C");
            var grossProfitPercent = dollarGrossProfit/_departmentSales;
            perfectGrossProfitLabel.Text = @"Percent Gross Profit: " + grossProfitPercent.ToString("P");
        }

        private void addRecordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            var form = new NewModifyRecord();
            form.ShowDialog();
            //One the user has closed the add record form, check to see if there is a newer date
            //available. If so, reload the form.
            var date = databaseReader.RetrieveMostRecentDate(databaseTracker.DatabaseConnectionString);
            if (date == _currentActiveDate) return;
            LoadDate(date);
        }

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

        private void modifyRecordMainMenu_Click(object sender, EventArgs e)
        {
            var form = new NewModifyRecord(_currentActiveDate);
            form.ShowDialog();
            //On return reload the date that was just modified by the modify record form.
            LoadDate(monthCalendar.SelectionStart);
        }

        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", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        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(monthCalendar.SelectionStart.ToShortDateString(),
                        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();
        }

        /// <summary>
        /// Fills the APC DataGridViews with the appropriate columns and starting row for the user to start
        /// entering data.
        /// </summary>
        private void ConstructApcDataGridViews()
        {
            //Construct a list of column names for the inventory/actual sales DataGridViews and the inventory DataGirdView.
            string[] saleColumnNames =
            {
                "AdItem", "Sold", "SalePrice", "TotalSales", "Cost", "ProfitReturn",
                "TotalProfitReturn"
            };
            string[] inventoryColumnNames =
            {
                "AdItem", "BeginningInventory", "Received", "Total", "EndingInventory"
            };

            foreach (var name in saleColumnNames)
            {
                var column = new DataGridViewTextBoxColumn
                {
                    Name = name,
                    HeaderText = TextFormat.AddSpacesToSentence(name, false),
                    ValueType = typeof(string),
                    SortMode = DataGridViewColumnSortMode.NotSortable,
                    MaxInputLength = 20
                };
                projectionsDataGridView.Columns.Add(column);
            }
            //Add the columns into the inventory DataGridView after setting their types.
            foreach (var name in inventoryColumnNames)
            {
                var column = new DataGridViewTextBoxColumn
                {
                    Name = name,
                    HeaderText = TextFormat.AddSpacesToSentence(name, false),
                    ValueType = typeof(string),
                    SortMode = DataGridViewColumnSortMode.NotSortable,
                    MaxInputLength = 20
                };
                inventoryDataGridView.Columns.Add(column);
            }
            //
            foreach (var name in saleColumnNames)
            {
                var column = new DataGridViewTextBoxColumn
                {
                    Name = name,
                    HeaderText = TextFormat.AddSpacesToSentence(name, false),
                    ValueType = typeof(string),
                    SortMode = DataGridViewColumnSortMode.NotSortable,
                    MaxInputLength = 20
                };
                actualSalesDataGridView.Columns.Add(column);
            }
        }

        /// <summary>
        /// Constructs the invoices DataGridView.
        /// </summary>
        private void ConstructInvoicesDataGridView()
        {
            string[] invoicesColumnNames =
            {
                "InvoiceDate", "Supplier", "InvoiceNumber", "InvoiceNetAmountAtCost",
                "InvoiceNetAmountExtendedRetail", "InvoiceNote"
            };

            foreach (var name in invoicesColumnNames)
            {
                var column = new DataGridViewTextBoxColumn
                {
                    Name = name,
                    HeaderText = TextFormat.AddSpacesToSentence(name, false),
                    ValueType = typeof(string),
                    SortMode = DataGridViewColumnSortMode.NotSortable,
                    MaxInputLength = 20
                };
                invoicesDataGridView.Columns.Add(column);
            }
        }

        private void LoadDate(DateTime date)
        {
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            if (monthCalendar.BoldedDates.Length == 0)
            {
                //The database is most likely empty so halt everything.
                dateTimeGroupBox.Text = @"The database appears to be empty.";
                modifyRecordMainMenu.Enabled = false;
                modifyRecordMainMenu.ToolTipText = @"There are no records to modify.";
                return;
            }
            modifyRecordMainMenu.Enabled = true;
            modifyRecordMainMenu.ToolTipText = @"";
            var dateId = databaseReader.RetrieveDateIdByDateString(date.ToString("d"),
                databaseTracker.DatabaseConnectionString);
            if (dateId == 0)
            {
                errorLabel.Text = @"Failed to get the date ID number, aborting load operation." + Environment.NewLine;
                return;
            }
            ClearForm();
            var projections = databaseReader.ReturnProjectionsTable(dateId, databaseTracker.DatabaseConnectionString);
            var inventory = databaseReader.ReturnInventoryTable(dateId, databaseTracker.DatabaseConnectionString);
            var actualSales = databaseReader.ReturnActualSales(dateId, databaseTracker.DatabaseConnectionString);
            LoadProjectionsTable(projections);
            LoadInventoryTable(inventory);
            LoadActualSalesTable(actualSales);
            var invoices = databaseReader.ReturnInvoiceTable(dateId, databaseTracker.DatabaseConnectionString);
            LoadInvoices(invoices);
            var comments = databaseReader.RetrieveComments(int.Parse(dateId.ToString()),
                databaseTracker.DatabaseConnectionString);
            if (comments.Count == 2)
            {
                commentsTextBox.Text = comments[1];
            }
            else
            {
                commentMainGroupBox.Text = @"Comments (None to Display)";
            }
            var weeklySales = databaseReader.ReturnWeeklySalesFromDateId(dateId,
                databaseTracker.DatabaseConnectionString);
            if (weeklySales.Rows.Count == 1)
            {
                LoadWeeklySales(weeklySales);
            }
            else
            {
                weeklySalesGroupBox.Text = @"Weekly Sales (Nothing to Display)";
            }

            var taxable = databaseReader.ReturnTaxableFromDateId(dateId, databaseTracker.DatabaseConnectionString);
            if (taxable.Rows.Count == 1)
            {
                LoadTaxable(taxable);
            }
            else
            {
                taxableGroupBox.Text = @"Taxable (Nothing to Display)";
            }
            var costAnalysis = databaseReader.ReturnCostAnalysis(dateId,
                databaseTracker.DatabaseConnectionString);
            if (costAnalysis.Rows.Count == 1)
            {
                LoadCostAnalysis(costAnalysis);
            }
            else
            {
                costAnalysisGroupBox.Text = @"Cost Analysis (Nothing to Display)";
            }
            CalculateProfitAnalysis();
            CalculateGrossProfit();
            monthCalendar.BoldedDates = databaseReader.RetrieveDates(databaseTracker.DatabaseConnectionString).ToArray();
            monthCalendar.SelectionStart = date;
            dateTimeGroupBox.Text = @"Loaded " + date.ToString("d");
        }

        private void LoadProjectionsTable(DataTable projections)
        {
            if (projections.Rows.Count == 0) return;
            var adSpecialIndex = -1;
            double totalSales = 0;
            double totalProfitReturn = 0;
            for (var rowIndex = 0; rowIndex < projections.Rows.Count; rowIndex++)
            {
                var newRow = new DataGridViewRow();
                for (var cellIndex = 1; cellIndex < projections.Rows[rowIndex].ItemArray.Length; cellIndex++)
                {
                    //ID and Ad Item.
                    if (cellIndex == 1)
                    {
                        var cell = new DataGridViewTextBoxCell
                        {
                            Value = projections.Rows[rowIndex].ItemArray[cellIndex].ToString()
                        };
                        newRow.Cells.Add(cell);
                        continue;
                    }
                    //String allowed columns
                    if (cellIndex > 1 && cellIndex <= 3)
                    {
                        if (projections.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty)
                        {
                            var cell = new DataGridViewTextBoxCell
                            {
                                Value = projections.Rows[rowIndex].ItemArray[cellIndex].ToString()
                            };
                            newRow.Cells.Add(cell);
                        }
                        else
                        {
                            var cell = new DataGridViewTextBoxCell {Value = string.Empty};
                            newRow.Cells.Add(cell);
                        }
                        continue;
                    }
                    //If the cell is meant to be summed into a totals roll add its contents to the total.
                    //If the cell is the total sales cell..
                    if (cellIndex == 4)
                    {
                        if (projections.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty &&
                            Math.Abs(double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString())) > 0)
                        {
                            totalSales += double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString());
                            var cell = new DataGridViewTextBoxCell
                            {
                                Value =
                                    double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString())
                                        .ToString("N2")
                            };
                            newRow.Cells.Add(cell);
                        }
                        else
                        {
                            var cell = new DataGridViewTextBoxCell {Value = string.Empty};
                            newRow.Cells.Add(cell);
                        }
                        continue;
                    }
                    //or the total profit return cell.
                    if (cellIndex == 7)
                    {
                        if (projections.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty &&
                            Math.Abs(double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString())) > 0)
                        {
                            totalProfitReturn += double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString());
                            var cell = new DataGridViewTextBoxCell
                            {
                                Value =
                                    double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString())
                                        .ToString("N2")
                            };
                            newRow.Cells.Add(cell);
                        }
                        else
                        {
                            var cell = new DataGridViewTextBoxCell {Value = string.Empty};
                            newRow.Cells.Add(cell);
                        }
                        continue;
                    }
                    //Everything in between the ad item cell and the row attribute cells.
                    if (cellIndex > 3 && cellIndex < 8)
                    {
                        if (Math.Abs(double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString())) > 0)
                        {
                            var cell = new DataGridViewTextBoxCell
                            {
                                Value =
                                    double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString())
                                        .ToString("N2")
                            };
                            newRow.Cells.Add(cell);
                        }
                        else
                        {
                            var cell = new DataGridViewTextBoxCell {Value = string.Empty};
                            newRow.Cells.Add(cell);
                        }
                        continue;
                    }
                    //Check the attribute cell.
                    if (cellIndex == 8)
                    {
                        var rowAttribute = int.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString());
                        switch (rowAttribute)
                        {
                            case 1:
                                //Header row
                                newRow.DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
                                break;
                            case 2:
                                //Member Row
                                newRow.DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
                                break;
                        }
                        continue;
                    }
                    //Check the group it is part of if any.
                    if (cellIndex != 9) continue;
                    //Check to see if this row belongs to an ad special group.
                    if (projections.Rows[rowIndex].ItemArray[cellIndex].ToString() == "0") continue;
                    //If the ad special index is not set, then create the ad special row with the human friendly group name.
                    if (adSpecialIndex != -1) continue;
                    var databaseTracker = new DatabaseTracker();
                    var databaseReader = new DatabaseReader();
                    var groupName =
                        databaseReader.ReturnGroupNameFromGroupId(
                            projections.Rows[rowIndex].ItemArray[cellIndex].ToString(),
                            databaseTracker.DatabaseConnectionString);
                    var adSpecialRow = new DataGridViewRow();
                    projectionsDataGridView.Rows.Add(adSpecialRow);
                    projectionsDataGridView.Rows[rowIndex].Cells[3].Value = groupName;
                    projectionsDataGridView.Rows[rowIndex].DefaultCellStyle.BackColor =
                        ApplicationColors.AdSpecial;
                    adSpecialIndex = rowIndex;
                }
                projectionsDataGridView.Rows.Add(newRow);
            }
            //Now add the totals row.
            var totalsRow = new DataGridViewRow();
            projectionsDataGridView.Rows.Add(totalsRow);
            projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[0].Value = "Total";
            projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[2].Style.Alignment =
                DataGridViewContentAlignment.MiddleRight;
            projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[2].Value = @"(A)";
            if (Math.Abs(totalSales) > 0)
            {
                projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[3].Value =
                    totalSales.ToString("N2");
            }
            projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[5].Style.Alignment =
                DataGridViewContentAlignment.MiddleRight;
            projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[5].Value = @"(B)";
            if (Math.Abs(totalProfitReturn) > 0)
            {
                projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[6].Value =
                    totalProfitReturn.ToString("N2");
            }
        }

        private void LoadInventoryTable(DataTable inventory)
        {
            if (inventory.Rows.Count == 0) return;
            var adSpecialIndex = -1;
            for (var rowIndex = 0; rowIndex < inventory.Rows.Count; rowIndex++)
            {
                var newRow = new DataGridViewRow();
                for (var cellIndex = 1; cellIndex < inventory.Rows[rowIndex].ItemArray.Length; cellIndex++)
                {
                    //String allowed columns
                    if (cellIndex < 6)
                    {
                        if (inventory.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty)
                        {
                            var cell = new DataGridViewTextBoxCell
                            {
                                Value = inventory.Rows[rowIndex].ItemArray[cellIndex].ToString()
                            };
                            newRow.Cells.Add(cell);
                        }
                        else
                        {
                            var cell = new DataGridViewTextBoxCell {Value = string.Empty};
                            newRow.Cells.Add(cell);
                        }
                        continue;
                    }
                    //Check the attribute cell.
                    if (cellIndex == 6)
                    {
                        var rowAttribute = int.Parse(inventory.Rows[rowIndex].ItemArray[cellIndex].ToString());
                        switch (rowAttribute)
                        {
                            case 1:
                                //Header row
                                newRow.DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
                                break;
                            case 2:
                                //Member Row
                                newRow.DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
                                break;
                        }
                        continue;
                    }
                    //Check the group it is part of if any.
                    if (cellIndex != 7) continue;
                    //Check to see if this row belongs to an ad special group.
                    if (inventory.Rows[rowIndex].ItemArray[cellIndex].ToString() == "0") continue;
                    //If the ad special index is not set, then create the ad special row with the human friendly group name.
                    if (adSpecialIndex != -1) continue;
                    var databaseTracker = new DatabaseTracker();
                    var databaseReader = new DatabaseReader();
                    var groupName =
                        databaseReader.ReturnGroupNameFromGroupId(
                            inventory.Rows[rowIndex].ItemArray[cellIndex].ToString(),
                            databaseTracker.DatabaseConnectionString);
                    var adSpecialRow = new DataGridViewRow();
                    inventoryDataGridView.Rows.Add(adSpecialRow);
                    inventoryDataGridView.Rows[rowIndex].Cells[2].Value = groupName;
                    inventoryDataGridView.Rows[rowIndex].DefaultCellStyle.BackColor =
                        ApplicationColors.AdSpecial;
                    adSpecialIndex = rowIndex;
                }
                inventoryDataGridView.Rows.Add(newRow);
            }
        }

        private void LoadActualSalesTable(DataTable actualSales)
        {
            if (actualSales.Rows.Count == 0) return;
            var adSpecialIndex = -1;
            double totalSales = 0;
            double totalProfitReturn = 0;
            for (var rowIndex = 0; rowIndex < actualSales.Rows.Count; rowIndex++)
            {
                var newRow = new DataGridViewRow();
                for (var cellIndex = 1; cellIndex < actualSales.Rows[rowIndex].ItemArray.Length; cellIndex++)
                {
                    //ID and Ad Item.
                    if (cellIndex == 1)
                    {
                        var cell = new DataGridViewTextBoxCell
                        {
                            Value = actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString()
                        };
                        newRow.Cells.Add(cell);
                        continue;
                    }
                    //String allowed columns
                    if (cellIndex > 1 && cellIndex <= 3)
                    {
                        if (actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty)
                        {
                            var cell = new DataGridViewTextBoxCell
                            {
                                Value = actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString()
                            };
                            newRow.Cells.Add(cell);
                        }
                        else
                        {
                            var cell = new DataGridViewTextBoxCell {Value = string.Empty};
                            newRow.Cells.Add(cell);
                        }
                        continue;
                    }
                    //If the cell is meant to be summed into a totals roll add its contents to the total.
                    //If the cell is the total sales cell..
                    if (cellIndex == 4)
                    {
                        if (actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty &&
                            Math.Abs(double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString())) > 0)
                        {
                            totalSales += double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString());
                            var cell = new DataGridViewTextBoxCell
                            {
                                Value =
                                    double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString())
                                        .ToString("N2")
                            };
                            newRow.Cells.Add(cell);
                        }
                        else
                        {
                            var cell = new DataGridViewTextBoxCell {Value = string.Empty};
                            newRow.Cells.Add(cell);
                        }
                        continue;
                    }
                    //or the total profit return cell.
                    if (cellIndex == 7)
                    {
                        if (actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty &&
                            Math.Abs(double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString())) > 0)
                        {
                            totalProfitReturn += double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString());
                            var cell = new DataGridViewTextBoxCell
                            {
                                Value =
                                    double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString())
                                        .ToString("N2")
                            };
                            newRow.Cells.Add(cell);
                        }
                        else
                        {
                            var cell = new DataGridViewTextBoxCell {Value = string.Empty};
                            newRow.Cells.Add(cell);
                        }
                        continue;
                    }
                    //Everything in between the ad item cell and the row attribute cells.
                    if (cellIndex > 3 && cellIndex < 8)
                    {
                        if (Math.Abs(double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString())) > 0)
                        {
                            var cell = new DataGridViewTextBoxCell
                            {
                                Value =
                                    double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString())
                                        .ToString("N2")
                            };
                            newRow.Cells.Add(cell);
                        }
                        else
                        {
                            var cell = new DataGridViewTextBoxCell {Value = string.Empty};
                            newRow.Cells.Add(cell);
                        }
                        continue;
                    }
                    //Check the attribute cell.
                    if (cellIndex == 8)
                    {
                        var rowAttribute = int.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString());
                        switch (rowAttribute)
                        {
                            case 1:
                                //Header row
                                newRow.DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
                                break;
                            case 2:
                                //Member Row
                                newRow.DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
                                break;
                        }
                        continue;
                    }
                    //Check the group it is part of if any.
                    if (cellIndex != 9) continue;
                    //Check to see if this row belongs to an ad special group.
                    if (actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() == "0") continue;
                    //If the ad special index is not set, then create the ad special row with the human friendly group name.
                    if (adSpecialIndex != -1) continue;
                    var databaseTracker = new DatabaseTracker();
                    var databaseReader = new DatabaseReader();
                    var groupName =
                        databaseReader.ReturnGroupNameFromGroupId(
                            actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString(),
                            databaseTracker.DatabaseConnectionString);
                    var adSpecialRow = new DataGridViewRow();
                    actualSalesDataGridView.Rows.Add(adSpecialRow);
                    actualSalesDataGridView.Rows[rowIndex].Cells[3].Value = groupName;
                    actualSalesDataGridView.Rows[rowIndex].DefaultCellStyle.BackColor =
                        ApplicationColors.AdSpecial;
                    adSpecialIndex = rowIndex;
                }
                actualSalesDataGridView.Rows.Add(newRow);
            }
            //Now add the totals row.
            var totalsRow = new DataGridViewRow();
            actualSalesDataGridView.Rows.Add(totalsRow);
            actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[0].Value = "Total";
            actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[2].Style.Alignment =
                DataGridViewContentAlignment.MiddleRight;
            actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[2].Value = @"(A)";
            if (Math.Abs(totalSales) > 0)
            {
                actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[3].Value =
                    totalSales.ToString("N2");
            }
            actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[5].Style.Alignment =
                DataGridViewContentAlignment.MiddleRight;
            actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[5].Value = @"(B)";
            if (Math.Abs(totalProfitReturn) > 0)
            {
                actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[6].Value =
                    totalProfitReturn.ToString("N2");
            }
        }

        private void LoadInvoices(DataTable invoices)
        {
            if (invoices.Rows.Count == 0) return;
            _totalInvoicePurchases = 0;
            for (var rowIndex = 0; rowIndex < invoices.Rows.Count; rowIndex++)
            {
                var row = new DataGridViewRow();
                for (var cellIndex = 1; cellIndex < invoices.Rows[rowIndex].ItemArray.Length; cellIndex++)
                {
                    var cell = new DataGridViewTextBoxCell();
                    switch (cellIndex)
                    {
                        //Apply formatting to the invoice date to trim the 12:00:00 time stamp.
                        case 1:
                            var date = DateTime.Parse(invoices.Rows[rowIndex].ItemArray[cellIndex].ToString());
                            cell.Value = date.ToString("d");
                            row.Cells.Add(cell);
                            continue;
                            //Apply formatting to the only cells that will have currency values in them.
                        case 4:
                            var netAmountAtCost = double.Parse(invoices.Rows[rowIndex].ItemArray[cellIndex].ToString());
                            if (netAmountAtCost.ToString("N2") != "0.00")
                            {
                                cell.Value = netAmountAtCost.ToString("N2");
                            }
                            row.Cells.Add(cell);
                            break;
                        case 5:
                            var netAmoundExtendedRetail = double.Parse(invoices.Rows[rowIndex].ItemArray[cellIndex].ToString());
                            if (netAmoundExtendedRetail.ToString("N2") != "0.00")
                            {
                                _totalInvoicePurchases += netAmoundExtendedRetail;
                                cell.Value = netAmoundExtendedRetail.ToString("N2");
                            }
                            row.Cells.Add(cell);
                            break;
                        default:
                            //No special formatting rules here so just put the value in and move on.     
                            cell.Value = invoices.Rows[rowIndex].ItemArray[cellIndex].ToString();
                            row.Cells.Add(cell);
                            break;
                    }
                }
                invoicesDataGridView.Rows.Add(row);
            }
            //Add the total purchases row to the invoice table.
            var totalPurchaesRow = new DataGridViewRow();
            invoicesDataGridView.Rows.Add(totalPurchaesRow);
            invoicesDataGridView.Rows[invoicesDataGridView.Rows.Count - 1].Cells[0].Value = @"Total Purchases";
            if (Math.Abs(_totalInvoicePurchases) > 0)
            {
                invoicesDataGridView.Rows[invoicesDataGridView.Rows.Count - 1].Cells[4].Value = _totalInvoicePurchases.ToString("N2");                
            }
        }

        private void LoadWeeklySales(DataTable weeklySales)
        {
            //Clear the department sales and prepare to add up a total.
            _departmentSales = 0;
            //Spin through the only row in the weekly sales table. Item in item 
            //array index zero (0) is the ID number of the weekly sales.
            for (var cellIndex = 1; cellIndex < weeklySales.Rows[0].ItemArray.Length; cellIndex++)
            {
                double dollarAmount;
                switch (cellIndex)
                {
                    case 1: //Sunday
                        dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
                        if (dollarAmount.ToString("N2") != "0.00")
                        {
                            _departmentSales += dollarAmount;
                            sundayWeeklySalesLabel.Text = @"Sunday: $" + dollarAmount.ToString("N2");
                        }
                        else
                        {
                            sundayWeeklySalesLabel.Text = @"Sunday: " + CheckForHoliday(DayOfWeek.Sunday);
                        }
                        break;
                    case 2: //Monday
                        dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
                        if (dollarAmount.ToString("N2") != "0.00")
                        {
                            _departmentSales += dollarAmount;
                            mondayWeeklySalesLabel.Text = @"Monday: $" + dollarAmount.ToString("N2");
                        }
                        else
                        {
                            mondayWeeklySalesLabel.Text = @"Monday: " + CheckForHoliday(DayOfWeek.Monday);
                        }
                        break;
                    case 3: //Tuesday
                        dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
                        if (dollarAmount.ToString("N2") != "0.00")
                        {
                            _departmentSales += dollarAmount;
                            tuesadayWeeklySalesLabel.Text = @"Tuesday: $" + dollarAmount.ToString("N2");
                        }
                        else
                        {
                            tuesadayWeeklySalesLabel.Text = @"Tuesday: " + CheckForHoliday(DayOfWeek.Tuesday);
                        }
                        break;
                    case 4: //Wednesday
                        dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
                        if (dollarAmount.ToString("N2") != "0.00")
                        {
                            _departmentSales += dollarAmount;
                            wednesdayWeeklySalesLabel.Text = @"Wednesday: $" + dollarAmount.ToString("N2");
                        }
                        else
                        {
                            wednesdayWeeklySalesLabel.Text = @"Wednesday: " + CheckForHoliday(DayOfWeek.Wednesday);
                        }
                        break;
                    case 5: //Thursday
                        dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
                        if (dollarAmount.ToString("N2") != "0.00")
                        {
                            _departmentSales += dollarAmount;
                            thursdayWeeklySalesLabel.Text = @"Thursday: $" + dollarAmount.ToString("N2");
                        }
                        else
                        {
                            thursdayWeeklySalesLabel.Text = @"Thursday: " + CheckForHoliday(DayOfWeek.Thursday);
                        }
                        break;
                    case 6: //Friday
                        dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
                        if (dollarAmount.ToString("N2") != "0.00")
                        {
                            _departmentSales += dollarAmount;
                            fridayWeeklySalesLabel.Text = @"Friday: $" + dollarAmount.ToString("N2");
                        }
                        else
                        {
                            fridayWeeklySalesLabel.Text = @"Friday: " + CheckForHoliday(DayOfWeek.Friday);
                        }
                        break;
                    case 7: //Saturday
                        dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
                        if (dollarAmount.ToString("N2") != "0.00")
                        {
                            _departmentSales += dollarAmount;
                            saturdayWeeklySalesLabel.Text = @"Saturday: $" + dollarAmount.ToString("N2");
                        }
                        else
                        {
                            saturdayWeeklySalesLabel.Text = @"Saturday: " + CheckForHoliday(DayOfWeek.Saturday);
                        }
                        break;
                    case 8: //Total Sales
                        dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
                        if (dollarAmount.ToString("N2") != "0.00")
                        {
                            totalWeeklySalesLabel.Text = @"Total Sales: $" + dollarAmount.ToString("N2");
                        }
                        else
                        {
                            totalWeeklySalesLabel.Text = @"Total Sales: ";
                        }
                        break;
                }
            }
        }

        private void LoadTaxable(DataTable taxable)
        {
            //Spin through the only row in the taxable table. Item in item 
            //array index zero (0) is the ID number of the weekly sales.
            for (var cellIndex = 1; cellIndex < taxable.Rows[0].ItemArray.Length; cellIndex++)
            {
                string formattedNumber;
                switch (cellIndex)
                {
                    case 1: //Sunday
                        formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
                        if (formattedNumber != "0.00")
                        {
                            sundayTaxableLabel.Text = @"Sunday: $" + formattedNumber;
                        }
                        else
                        {
                            sundayTaxableLabel.Text = @"Sunday: " + CheckForHoliday(DayOfWeek.Sunday);
                        }
                        break;
                    case 2: //Monday
                        formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
                        if (formattedNumber != "0.00")
                        {
                            mondayTaxableLabel.Text = @"Monday: $" + formattedNumber;
                        }
                        else
                        {
                            mondayTaxableLabel.Text = @"Monday: " + CheckForHoliday(DayOfWeek.Monday);
                        }
                        break;
                    case 3: //Tuesday
                        formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
                        if (formattedNumber != "0.00")
                        {
                            tuesdayTaxableLabel.Text = @"Tuesday: $" + formattedNumber;
                        }
                        else
                        {
                            tuesdayTaxableLabel.Text = @"Tuesday: " + CheckForHoliday(DayOfWeek.Tuesday);
                        }
                        break;
                    case 4: //Wednesday
                        formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
                        if (formattedNumber != "0.00")
                        {
                            wednesdayTaxableLabel.Text = @"Wednesday: $" + formattedNumber;
                        }
                        else
                        {
                            wednesdayTaxableLabel.Text = @"Wednesday: " + CheckForHoliday(DayOfWeek.Wednesday);
                        }
                        break;
                    case 5: //Thursday
                        formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
                        if (formattedNumber != "0.00")
                        {
                            thursdayTaxableLabel.Text = @"Thursday: $" + formattedNumber;
                        }
                        else
                        {
                            thursdayTaxableLabel.Text = @"Thursday: " + CheckForHoliday(DayOfWeek.Thursday);
                        }
                        break;
                    case 6: //Friday
                        formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
                        if (formattedNumber != "0.00")
                        {
                            fridayTaxableLabel.Text = @"Friday: $" + formattedNumber;
                        }
                        else
                        {
                            fridayTaxableLabel.Text = @"Friday: " + CheckForHoliday(DayOfWeek.Friday);
                        }
                        break;
                    case 7: //Saturday
                        formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
                        if (formattedNumber != "0.00")
                        {
                            saturdayTaxableLabel.Text = @"Saturday: $" + formattedNumber;
                        }
                        else
                        {
                            saturdayTaxableLabel.Text = @"Saturday: " + CheckForHoliday(DayOfWeek.Saturday);
                        }
                        break;
                    case 8: //Total Taxable
                        formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
                        if (formattedNumber != "0.00")
                        {
                            totalTaxableLabel.Text = @"Total Taxable: $" + formattedNumber;
                        }
                        break;
                }
            }
        }

        private void LoadCostAnalysis(DataTable costAnalysis)
        {
            //Spin through the only row in the taxable table. Item in item 
            //array index zero (0) is the ID number of the weekly sales.
            for (var cellIndex = 1; cellIndex < costAnalysis.Rows[0].ItemArray.Length; cellIndex++)
            {
                string formattedNumber;
                switch (cellIndex)
                {
                    case 1: //Sales per man hour
                        formattedNumber = double.Parse(costAnalysis.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
                        if (formattedNumber != "0.00")
                        {
                            salesPerManHourLabel.Text = @"Sales Per Man Hour: $" + formattedNumber;
                        }
                        break;
                    case 2: //Salary Percentage
                        formattedNumber = double.Parse(costAnalysis.Rows[0].ItemArray[cellIndex].ToString()).ToString("P2");
                        if (formattedNumber != "0.00")
                        {
                            salaryPercentageLabel.Text = @"Salary Percentage: " + formattedNumber;
                        }
                        break;
                    case 3: //Salary Dollars
                        formattedNumber = double.Parse(costAnalysis.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
                        if (formattedNumber != "0.00")
                        {
                            salaryDollarsLabel.Text = @"Salary Dollars: $" + formattedNumber;
                        }
                        break;
                    case 4: //Supplies
                        formattedNumber = double.Parse(costAnalysis.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
                        if (formattedNumber != "0.00")
                        {
                            suppliesLabel.Text = @"Supplies: $" + formattedNumber;
                        }
                        break;
                }
            }
        }

        private string CheckForHoliday(DayOfWeek day)
        {
            var holidayText = string.Empty;
            //Get the currently selected date.
            var date = monthCalendar.SelectionStart;
            //Now make sure the selected day on the calendar (the date that came from the database) is not the same
            //as the day provided, unless the day is Saturday. If the end of week date is not on a Saturday and the 
            //supplied day is Monday, than subtracting 5 would yield an incorrect date.
            if (date.DayOfWeek == DayOfWeek.Saturday)
            {
                switch (day)
                {
                    case DayOfWeek.Sunday:
                        date = date.AddDays(-6);
                        break;
                    case DayOfWeek.Monday:
                        date = date.AddDays(-5);
                        break;
                    case DayOfWeek.Tuesday:
                        date = date.AddDays(-4);
                        break;
                    case DayOfWeek.Wednesday:
                        date = date.AddDays(-3);
                        break;
                    case DayOfWeek.Thursday:
                        date = date.AddDays(-2);
                        break;
                    case DayOfWeek.Friday:
                        date = date.AddDays(-1);
                        break;
                }
            }
            var holiday = Holiday.IsHoliday(date);
            switch (holiday)
            {
                case Holidays.Thanksgiving:
                case Holidays.Christmas:    
                case Holidays.NewYearsDay:            
                    holidayText = @"Closed for " + TextFormat.AddSpacesToSentence(holiday.ToString(), false);
                    break;
            }
            return holidayText;
        }

        private void ValidateDateChanged(object sender, DateRangeEventArgs e)
        {
            if (e.Start == _currentActiveDate || !monthCalendar.BoldedDates.Contains(e.Start)) return;
            _currentActiveDate = e.Start;
            //Load the specified date from the database.
            LoadDate(e.Start);
        }

        private void ClearForm()
        {
            projectionsDataGridView.Rows.Clear();
            inventoryDataGridView.Rows.Clear();
            actualSalesDataGridView.Rows.Clear();
            invoicesDataGridView.Rows.Clear();
            commentsTextBox.Text = string.Empty;
            commentMainGroupBox.Text = @"Comments";
            dateTimeGroupBox.Text = string.Empty;
            salesPerManHourLabel.Text = @"Sales Per Man Hour:";
            salaryPercentageLabel.Text = @"Salary Percentage:";
            salaryDollarsLabel.Text = @"Salary Dollars:";
            suppliesLabel.Text = @"Supplies:";
            costAnalysisGroupBox.Text = @"Cost Analysis";
            sundayWeeklySalesLabel.Text = @"Sunday: ";
            mondayWeeklySalesLabel.Text = @"Monday: ";
            tuesadayWeeklySalesLabel.Text = @"Tuesday: ";
            wednesdayWeeklySalesLabel.Text = @"Wednesday: ";
            thursdayWeeklySalesLabel.Text = @"Wednesday: ";
            fridayWeeklySalesLabel.Text = @"Friday: ";
            saturdayWeeklySalesLabel.Text = @"Saturday: ";
            totalWeeklySalesLabel.Text = @"Total Sales: ";
            weeklySalesGroupBox.Text = @"Weekly Sales";
            sundayTaxableLabel.Text = @"Sunday: ";
            mondayTaxableLabel.Text = @"Monday: ";
            tuesdayTaxableLabel.Text = @"Tuesday: ";
            wednesdayTaxableLabel.Text = @"Wednesday: ";
            thursdayTaxableLabel.Text = @"Wednesday: ";
            fridayTaxableLabel.Text = @"Friday: ";
            saturdayTaxableLabel.Text = @"Saturday: ";
            totalTaxableLabel.Text = @"Total: ";
            taxableGroupBox.Text = @"Taxable";
            departmentSalesLabel.Text = @"Department Sales: ";
            salesProducedLabel.Text = @"Sales Produced By Ad Items (A):";
            remainingSalesLabel.Text = @"Remaining Sales:";
            totalProfitFromAdItemsLabel.Text = @"Total Profit Return" + Environment.NewLine + @" From Ad Items (B): ";
            totalProfitReturnFromRemaingLabel.Text = @"Total Profit Return" + Environment.NewLine + @" From Remaining Sales: ";
            totalProfitReturnLabel.Text = @"Total Profit Return: ";
            grossProfitTotalSales.Text = @"Total Sales:";
            grossProfitLessCostOfSales.Text = @"Less Cost of Sales: ";
            grossProfitDollarGrossProfitLabel.Text = @"Dollar Gross Profit: ";
            perfectGrossProfitLabel.Text = @"Percent Gross Profit: ";
            grossProfitEstimatedWeeklyDeptmartmentExpenseLabel.Text = @"Estimated Weekly" + Environment.NewLine + @" Department Expense: ";
        }

        private void debugToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var form = new DebugDatabaseConverter();
            form.ShowDialog();
            RefreshDateListing();
        }

        private void RefreshDateListing()
        {
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            monthCalendar.BoldedDates = databaseReader.RetrieveDates(databaseTracker.DatabaseConnectionString).ToArray();
        }

        public enum FormDefaultRoll
        {
            AddNewRecord = 0,
            ModifyExistingRecord = 1
        }

        private void clearSelectedDateToolsMainMenu_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show(@"Are you sure you want to delete all records for the date " + _currentActiveDate.ToShortDateString() + @"?", @"Clear Date", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.No)
            {
                return;
            }
            var dbT = new DatabaseTracker();
            var dbW = new DatabaseWriter(dbT.DatabaseConnectionString);
            var dbR = new DatabaseReader();
            var dateId = dbR.RetrieveDateIdByDateString(_currentActiveDate.ToShortDateString(), dbT.DatabaseConnectionString);
            if (dateId != 0)
            {
                if (dbW.ClearDateById(dateId))
                {
                    RefreshDateListing();
                    var date = dbR.RetrieveMostRecentDate(dbT.DatabaseConnectionString);
                    LoadDate(date);
                }
                else
                {
                    errorLabel.Text = @"Failed to clear the selected date.";
                }
            }
            else
            {
                errorLabel.Text = @"Failed to get the date ID number.";
            }
        }
    }
}
    //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();
        }
    }
