using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Data;

namespace AdvertsingProfitControl
{
    internal class DatabaseReader
    {
        public string GetDatabaseVersion(string connectionString)
        {
            var versionNumber = "0.0.0.0";
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT VersionNumber FROM Version"
            };
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using (var reader = oleDbCommand.ExecuteReader())
                    {
                        while (reader != null && reader.Read())
                        {
                            versionNumber = reader[0].ToString();
                        }
                    }
                }
            }

            return versionNumber;
        }

        #region Date Functions
        /// <summary>
        /// Retrieves the most recent date's ID from the database.
        /// </summary>
        /// <param name="connectionString">The connection string for the database.</param>
        /// <returns>The ID number as a string.</returns>
        public string RetrieveMostRecentDateId(string connectionString)
        {
            var dateId = "0";
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT WeekEnding.ID FROM WeekEnding WHERE WeekEnding.EndOfWeekDate = (SELECT MAX(WeekEnding.EndOfWeekDate) FROM WeekEnding)"
            };
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using (var reader = oleDbCommand.ExecuteReader())
                    {
                        while (reader != null && reader.Read())
                        {
                            dateId = reader[0].ToString();
                        }
                    }
                }
            }

            return dateId;
        }

        public string RetrieveDateIdByDateString(string dateString, string connectionString)
        {
            var dateId = "0";
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT WeekEnding.ID FROM WeekEnding WHERE WeekEnding.EndOfWeekDate = ?"
            };
            oleDbCommand.Parameters.AddWithValue("DateString", dateString);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using (var reader = oleDbCommand.ExecuteReader())
                    {
                        while(reader != null && reader.Read())
                        {
                            dateId = reader[0].ToString();
                        }
                    }
                }
            }

            return dateId;
        }

        public string RetrieveDateStringById(string dateId, string connectionString)
        {
            string dateString = "";
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT WeekEnding.EndOfWeekDate FROM WeekEnding WHERE WeekEnding.ID = ? ORDER BY EndOfWeekDate ASC"
            };
            oleDbCommand.Parameters.AddWithValue("DateID", dateId);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using(var reader = oleDbCommand.ExecuteReader())
                    {
                        while(reader != null && reader.Read())
                        {
                            dateString = reader[0].ToString();
                        }
                    }
                }
            }

            return dateString;
        }

        public List<string> RetrieveUniqueYearsList(string connectionString)
        {
            var datesList = new List<string>();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT Distinct YEAR(EndOfWeekDate) FROM WeekEnding"
            };
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using(var reader = oleDbCommand.ExecuteReader())
                    {
                        while(reader != null && reader.Read())
                        {
                            datesList.Add(reader[0].ToString());
                        }
                    }
                }
            }

            return datesList;
        }

        public List<string> RetrieveUniqueMonthsList(string year, string connectionString)
        {
            var datesList = new List<string>();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT Distinct MONTH(EndOfWeekDate) FROM WeekEnding WHERE YEAR(EndOfWeekDate) = ?"
            };
            oleDbCommand.Parameters.AddWithValue("Year", year);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using (var reader = oleDbCommand.ExecuteReader())
                    {
                        while (reader != null && reader.Read())
                        {
                            datesList.Add(reader[0].ToString());
                        }
                    }
                }
            }

            return datesList;
        }

        public DateTime RetrieveMostRecentDateString(string connectionString)
        {
            DateTime dateTimeObject = new DateTime();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT WeekEnding.EndOfWeekDate FROM WeekEnding WHERE WeekEnding.EndOfWeekDate = (SELECT MAX(WeekEnding.EndOfWeekDate) FROM WeekEnding)"
            };
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using(var reader = oleDbCommand.ExecuteReader())
                    {
                        while(reader != null && reader.Read())
                        {
                            dateTimeObject = (DateTime) reader[0];
                        }
                    }
                }
            }

            return dateTimeObject;
        }

        /// <summary>
        /// Returns a list of dates by the year supplied.
        /// </summary>
        /// <returns></returns>
        public List<DateTime> RetrieveDateListByYear(string year, string connectionString)
        {
            var datesList = new List<DateTime>();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT EndOfWeekDate FROM WeekEnding WHERE YEAR(EndOfWeekDate) = ? ORDER BY EndOfWeekDate ASC"
            };
            oleDbCommand.Parameters.AddWithValue("Year", year);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using(var reader = oleDbCommand.ExecuteReader())
                    {
                        while(reader != null && reader.Read())
                        {
                            datesList.Add((DateTime)reader[0]);
                        }
                    }
                }
            }

            return datesList;
        }

        #endregion

        #region Ad Item Functions

        public string RetrieveAdItemId(string adItemName, string connectionString)
        {
            var id = "0";
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT AdItem.ID FROM AdItem WHERE UCASE(AdItem.AdItem) = UCASE(?)"
            };
            oleDbCommand.Parameters.AddWithValue("AdItemName", adItemName);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using (var reader = oleDbCommand.ExecuteReader())
                    {
                        while (reader != null && reader.Read())
                        {
                            id = reader[0].ToString();
                        }
                    }
                }
            }
            return id;
        }

        public List<string> RetrieveUsedAdItemListByDateId(string dateId, string connectionString)
        {
            var adItemList = new List<string>();
            var oleDbCommand = new OleDbCommand
            {
                CommandText = "SELECT AdItem.AdItem, APC.RowAttribute, APC.FK_GroupID FROM (APC INNER JOIN AdItem ON APC.FK_AdItemID = AdItem.ID) WHERE FK_DateID = ? ORDER BY RowPosition ASC"
            };
            oleDbCommand.Parameters.AddWithValue("DateID", dateId);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;
            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using (var reader = oleDbCommand.ExecuteReader())
                    {
                        while (reader != null && reader.Read())
                        {
                            if (reader["FK_GroupID"].ToString() != "" && int.Parse(reader["FK_GroupID"].ToString()) >= 3)
                            {
                                adItemList.Add(reader[0] + ":2");
                            }
                            else
                            {
                                adItemList.Add(reader[0] + ":1");                                
                            }

                        }
                    }
                }
            }

            return adItemList;
        }

        public List<string> RetrieveAdItemListByLetter(string connectionString, string letterFilter = "All")
        {
            var adItemsList = new List<string>();
            var oleDbCommand = new OleDbCommand();
            if(letterFilter == "All")
            {
                oleDbCommand.CommandText = "SELECT AdItem FROM AdItem ORDER BY AdItem ASC";
            }
            else
            {
                oleDbCommand.CommandText = "SELECT AdItem FROM AdItem WHERE LEFT(AdItem, 1) = ? ORDER BY AdItem ASC";
                oleDbCommand.Parameters.AddWithValue("Filter", letterFilter);
            }
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using (var reader = oleDbCommand.ExecuteReader())
                    {
                        while (reader != null && reader.Read())
                        {
                            adItemsList.Add((reader[0].ToString()));
                        }
                    }
                }
            }

            return adItemsList;
        } 

        #endregion

        #region Comment Functions

        public string RetrieveComments(string dateId, string connectionString)
        {
            var comments = "";
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT Comment.Comment FROM Comment WHERE Comment.FK_DateID = ?"
            };
            oleDbCommand.Parameters.AddWithValue("DateID", dateId);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using(var reader = oleDbCommand.ExecuteReader())
                    {
                        while(reader != null && reader.Read())
                        {
                            comments = reader[0].ToString();
                        }
                    }
                }
            }

            return comments;
        }

        #endregion

        #region Ad Special Functions

        public string RetrieveGroupIdByString(string groupName, string connectionString)
        {
            var groupId = "0";
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT GroupCategory.ID FROM GroupCategory WHERE GroupCategory.GroupDescription = ?"
            };
            oleDbCommand.Parameters.AddWithValue("GroupName", groupName);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using(var reader = oleDbCommand.ExecuteReader())
                    {
                        while(reader != null && reader.Read())
                        {
                            groupId = reader[0].ToString();
                        }
                    }
                }
            }

            return groupId;
        }

        public List<string> ReturnGroupNameList(string connectionString)
        {
            var groupNames = new List<string>();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT GroupCategory.GroupDescription FROM GroupCategory WHERE NOT GroupDescription = 'HeaderRow' AND NOT GroupDescription = 'MemberRow'"
            };
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using(var reader = oleDbCommand.ExecuteReader())
                    {
                        while(reader != null && reader.Read())
                        {
                            groupNames.Add(reader[0].ToString());
                        }
                    }
                }
            }

            return groupNames;
        }

        public DataTable ReturnGroupIdTable(string dateId, string connectionString)
        {
            var dataTable = new DataTable();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT APC.FK_GroupID FROM APC WHERE FK_DateID = ?"
            };
            oleDbCommand.Parameters.AddWithValue("DateID", dateId);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using (var dataAdapter = new OleDbDataAdapter(oleDbCommand))
                    {
                        dataAdapter.Fill(dataTable);
                    }
                }
            }

            return dataTable;
        }

        public string ReturnGroupNameFromGroupId(string id, string connectionString)
        {
            var name = "";
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT GroupDescription FROM GroupCategory WHERE ID = ?"
            };
            oleDbCommand.Parameters.AddWithValue("GroupID", id);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using (var reader = oleDbCommand.ExecuteReader())
                    {
                        while (reader != null && reader.Read())
                        {
                            name = reader[0].ToString();
                        }
                    }
                }
            }

            return name;
        }

        public AutoCompleteStringCollection RetrieveAdSpecialList(string connectionString)
        {
            var adSpecialList = new AutoCompleteStringCollection();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "Select GroupDescription FROM GroupCategory WHERE NOT GroupDescription = 'HeaderRow' AND NOT GroupDescription = 'MemberRow'"
            };
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using (var reader = oleDbCommand.ExecuteReader())
                    {
                        while (reader != null && reader.Read())
                        {
                            adSpecialList.Add(reader[0].ToString());
                        }
                    }
                }
            }

            return adSpecialList;
        }
        #endregion

        #region AutoComplete Functions

        public List<string> GetAdItemsSuggestionList(string connectionString)
        {
            var autoCompleteList = new List<string>();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT AdItem.AdItem FROM AdItem ORDER BY AdItem.AdItem ASC"
            };
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using(var reader = oleDbCommand.ExecuteReader())
                    {
                        while(reader != null && reader.Read())
                        {
                            autoCompleteList.Add(reader[0].ToString());
                        }
                    }
                }
            }
            
            return autoCompleteList;
        }

        public AutoCompleteStringCollection GetSupplierSuggestionList(string connectionString)
        {
            var autoCompleteList = new AutoCompleteStringCollection();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT SupplierName FROM Supplier ORDER BY SupplierName ASC"
            };
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;
            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using(var reader = oleDbCommand.ExecuteReader())
                    {
                        while(reader != null && reader.Read())
                        {
                            autoCompleteList.Add(reader[0].ToString());
                        }
                    }
                }
            }

            return autoCompleteList;
        }

        #endregion

        #region Table Return Functions

        public DataTable ReturnApcTableForReport(string dateId, string connectionString)
        {
            var dataTable = new DataTable();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT AdItem.AdItem, APC.ProjectionSold, APC.ProjectionSalePrice, APC.ProjectionTotalSales, APC.ProjectionCost, APC.ProjectionProfitReturn, APC.ProjectionTotalProfitReturn, APC.BeginingInventory, APC.Received, APC.TotalInventory, APC.EndingInventory, APC.ActualSold, APC.ActualSalePrice, APC.ActualTotalSales, APC.ActualCost, APC.ActualProfitReturn, APC.ActualTotalProfitReturn, RowAttribute, FK_GroupID FROM (AdItem INNER JOIN APC ON AdItem.ID = APC.FK_AdItemID) WHERE FK_DateID = ? ORDER BY RowPosition ASC"
            };
            oleDbCommand.Parameters.AddWithValue("DateID", dateId);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using (var dataAdapter = new OleDbDataAdapter(oleDbCommand))
                    {
                        dataAdapter.Fill(dataTable);
                    }
                }
            }

            return dataTable;
        }

        public DataTable ReturnProjectionsTable(string dateId, string connectionString)
        {
            var dataTable = new DataTable();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT AdItem.AdItem, APC.ProjectionSold, APC.ProjectionSalePrice, APC.ProjectionTotalSales, APC.ProjectionCost, APC.ProjectionProfitReturn, APC.ProjectionTotalProfitReturn, RowAttribute, FK_GroupID FROM (AdItem INNER JOIN APC ON AdItem.ID = APC.FK_AdItemID) WHERE FK_DateID = ? ORDER BY RowPosition ASC"
            };
            oleDbCommand.Parameters.AddWithValue("DateID", dateId);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using (var dataAdapter = new OleDbDataAdapter(oleDbCommand))
                    {
                        dataAdapter.Fill(dataTable);
                    }
                }
            }
            return dataTable;
        }

        public DataTable ReturnActualSales(string dateId, string connectionString)
        {
            var dataTable = new DataTable();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT AdItem.AdItem, APC.ActualSold, APC.ActualSalePrice, APC.ActualTotalSales, APC.ActualCost, APC.ActualProfitReturn, APC.ActualTotalProfitReturn, RowAttribute, FK_GroupID FROM (AdItem INNER JOIN APC ON AdItem.ID = APC.FK_AdItemID) WHERE FK_DateID = ? ORDER BY RowPosition ASC"
            };
            oleDbCommand.Parameters.AddWithValue("DateID", dateId);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using (var dataAdapter = new OleDbDataAdapter(oleDbCommand))
                    {
                        dataAdapter.Fill(dataTable);
                    }
                }
            }
            return dataTable;
        }

        public DataTable ReturnInventoryTable(string dateId, string connectionString)
        {
            var dataTable = new DataTable();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT AdItem.AdItem, APC.BeginingInventory, APC.Received, APC.TotalInventory, APC.EndingInventory, RowAttribute, FK_GroupID FROM (AdItem INNER JOIN APC ON AdItem.ID = APC.FK_AdItemID) WHERE FK_DateID = ? ORDER BY RowPosition ASC"
            };
            oleDbCommand.Parameters.AddWithValue("DateID", dateId);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using(var dataAdapter = new OleDbDataAdapter(oleDbCommand))
                    {
                        dataAdapter.Fill(dataTable);
                    }
                }
            }
            return dataTable;
        }


        public DataTable ReturnInvoiceTable(string dateId, string connectionString)
        {
            var dataTable = new DataTable();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT Supplier.SupplierName, Invoice.InvoiceNumber, Invoice.InvoiceDate, Invoice.InvoiceNetAmountAtCost, Invoice.InvoiceNetAmount, Invoice.InvoiceNote FROM (Supplier INNER JOIN Invoice ON Supplier.ID = Invoice.FK_Supplier) WHERE FK_DateID = ?"
            };
            oleDbCommand.Parameters.AddWithValue("DateID", dateId);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    using(var adapter = new OleDbDataAdapter(oleDbCommand))
                    {
                        adapter.Fill(dataTable);
                    }
                }
            }

            return dataTable;
        }

        public DataTable ReturnWeeklySalesFromDateId(string dateId, string connectionString)
        {
            var dataTable = new DataTable();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT WeeklySales.Sunday, WeeklySales.Monday, WeeklySales.Tuesday, WeeklySales.Wednesday, WeeklySales.Thursday, WeeklySales.Friday, WeeklySales.Saturday, WeeklySales.TotalSales FROM WeeklySales WHERE FK_DateID = ?"
            };
            oleDbCommand.Parameters.AddWithValue("DateID", dateId);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;
            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using(var dataAdapter = new OleDbDataAdapter(oleDbCommand))
                    {
                        dataAdapter.Fill(dataTable);
                    }
                }
            }

            return dataTable;
        }


        public DataTable ReturnWeekEndingTable(string connectionString)
        {
            var dataTable = new DataTable();
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT EndOfWeekDate FROM WeekEnding ORDER BY EndOfWeekDate ASC"
            };
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using(var dataAdapter = new OleDbDataAdapter(oleDbCommand))
                    {
                        dataAdapter.Fill(dataTable);
                    }
                }
            }

            return dataTable;

        }

        #endregion

        #region Supplier And Invoices Functions

        public string RetrieveSupplierNameById(string supplierId, string connectionString)
        {
            var supplierName = "";
            var oleDbCommand = new OleDbCommand()
            {
                CommandText = "SELECT SupplierName FROM Supplier WHERE ID = ?"
            };
            oleDbCommand.Parameters.AddWithValue("ID", supplierId);
            var connection = new OleDbConnection(connectionString);
            oleDbCommand.Connection = connection;

            using (connection)
            {
                using (oleDbCommand)
                {
                    connection.Open();
                    using(var reader = oleDbCommand.ExecuteReader())
                    {
                        while(reader != null && reader.Read())
                        {
                            supplierName = reader[0].ToString();
                        }
                    }
                }
            }

            return supplierName;
        }

        #endregion
    }
}
