using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;

namespace CheckFirmwareUpgradeEligibility
{
	#region "Summary"

	/* Project-Firmware Upgrade
	 * Description:check user eligibility.
	 * Created By-Xavient Offshore
	 * Created Date-17 Dec 2013
     *
     * 
     * 
     * 
     * 
     * 
     * 
	*/
	#endregion

	#region "Interface declaration"

	interface ICheckLegacyWIFI
	{
		string checkEligibilityStatus(ClsCheckLegacyWIFI obj);
	}

	#endregion

	#region "Class declaration and Implements Interface"

	public class ClsCheckLegacyWIFI : ICheckLegacyWIFI
	{
		#region "Private Variable Declaration"

		private string _AccountNumber;
		private string _MacAddress;
		private string _PhoneNumber;
        private string _ZipCodePhone;
        private string _ZipCodeAccount;

		#endregion

		#region "Public Property Declaration"

		public string AccountNumber
		{
			get
			{
				return this._AccountNumber;
			}
			set
			{
				this._AccountNumber = value;
			}
		}

		public string MacAddress
		{
			get
			{
				return this._MacAddress;
			}
			set
			{
				this._MacAddress = value;
			}
		}

		public string PhoneNumber
		{
			get
			{
				return this._PhoneNumber;
			}
			set
			{
				this._PhoneNumber = value;
			}
		}

        public string ZipCodePhone
		{
			get
			{
                return this._ZipCodePhone;
			}
			set
			{
                this._ZipCodePhone = value;
            }
        }

        public string ZipCodeAccount
        {
            get
            {
                return this._ZipCodeAccount;
            }
            set
            {
                this._ZipCodeAccount = value;
			}
		}

		#endregion

		#region "Public Methods"

		public string checkEligibilityStatus(ClsCheckLegacyWIFI objClsCheckLegacyWIFI)
		{
			string strReturnMessage = string.Empty;

			try
			{
				strReturnMessage = CheckInputValidation(objClsCheckLegacyWIFI);
				if (strReturnMessage == "")
				{
					if (objClsCheckLegacyWIFI.MacAddress != "")
					{
						strReturnMessage = GetEligibilityStatussMAC(objClsCheckLegacyWIFI);
					}
                    else if (objClsCheckLegacyWIFI.ZipCodePhone != "" && objClsCheckLegacyWIFI.PhoneNumber != "")
                    {
                        bool val = Regex.IsMatch(objClsCheckLegacyWIFI.ZipCodePhone, @"^\d+$");
                        bool valPhone = ValidatePhoneNumber(objClsCheckLegacyWIFI.PhoneNumber);
                        if (val == false || valPhone == false)
					{
                            strReturnMessage = "10 digit phone number and 5 digit zipcode are required.";

                        }
                        else if (objClsCheckLegacyWIFI.ZipCodePhone.Length != 5)
                        {
                            strReturnMessage = "10 digit phone number and 5 digit zipcode are required.";
                        }
                        else
                        {
                            strReturnMessage = GetEligibilityStatussZipPhone(objClsCheckLegacyWIFI);
                        }
                      

						}
                    else if (objClsCheckLegacyWIFI.AccountNumber != "" && objClsCheckLegacyWIFI.ZipCodeAccount != "")
						{
                        bool valAcc = Regex.IsMatch(objClsCheckLegacyWIFI.AccountNumber, @"^\d+$");
                        bool valZip = Regex.IsMatch(objClsCheckLegacyWIFI.ZipCodeAccount, @"^\d+$");

                        if (valAcc == false || valZip == false)
                            {
                            strReturnMessage = "A 16 digit account number and 5 digit Zipcode are required.";

                            }
                        else if (objClsCheckLegacyWIFI.ZipCodeAccount.Length != 5)
                            {
                            strReturnMessage = "A 16 digit account number and 5 digit Zipcode are required.";
                            }
                        else if (objClsCheckLegacyWIFI.AccountNumber.Length != 16)
                            {
                            strReturnMessage = "A 16 digit account number and 5 digit Zipcode are required.";
                        }
						else
						{
                            strReturnMessage = GetEligibilityStatussZIPAcc(objClsCheckLegacyWIFI);
						}


					}
				}
			}
			catch (Exception ex)
			{
				strReturnMessage = ex.Message.ToString();
			}

               
                
               
			return strReturnMessage;
		}

		// Check Inputs validation entered by user for blank and digits
        
		private string CheckInputValidation(ClsCheckLegacyWIFI objClsCheckLegacyWIFI)
		{
			string strReturnMessage = string.Empty;
           if ((objClsCheckLegacyWIFI.AccountNumber == "") && (objClsCheckLegacyWIFI.ZipCodePhone == "") && (objClsCheckLegacyWIFI.ZipCodeAccount == "") && (objClsCheckLegacyWIFI.PhoneNumber == "") && (objClsCheckLegacyWIFI.MacAddress == ""))
			{
				strReturnMessage = "Form is missing required component, check your entries and try again.";
			}
			else if (objClsCheckLegacyWIFI.MacAddress != "")
			{
				string strSql = string.Empty;
				strSql = " select PATINDEX('%[^0-9A-Fa-f]%','" + objClsCheckLegacyWIFI.MacAddress + "')";
				int retval;
				SqlConnection SqlConn = GetConectionString();
				SqlCommand Sqlcmd = new SqlCommand(strSql, SqlConn);
				SqlConn.Open();
				retval = (int)Sqlcmd.ExecuteScalar();
				SqlConn.Close();

				if (retval > 0)
				{
                    strReturnMessage = "Your MAC address requires 12 characters, alpha and numeric.";
				}
				else if (objClsCheckLegacyWIFI.MacAddress.Length != 12)
				{
					strReturnMessage = "Your MAC address requires 12 characters, alpha and numeric.";
				}
            }
           else if (objClsCheckLegacyWIFI.PhoneNumber != "")
           {
               bool valPhone = ValidatePhoneNumber(objClsCheckLegacyWIFI.PhoneNumber);
               bool valZip = Regex.IsMatch(objClsCheckLegacyWIFI.ZipCodePhone, @"^\d+$");
               if (valPhone == false || valZip==false )
               {
                   strReturnMessage = "A 10 digit phone number and 5 digit zipcode are required.";
               }
               else if (objClsCheckLegacyWIFI.ZipCodePhone =="")
               {
                   strReturnMessage = "A 10 digit phone number and 5 digit zipcode are required.";
               }
               else if (objClsCheckLegacyWIFI.ZipCodePhone.Length != 5)
               {
                   strReturnMessage = "A 10 digit phone number and 5 digit zipcode are required.";
			}
             
              
           }
           else if (objClsCheckLegacyWIFI.ZipCodePhone != "")
           {
               bool valPhone = ValidatePhoneNumber(objClsCheckLegacyWIFI.PhoneNumber);
               bool valZip = Regex.IsMatch(objClsCheckLegacyWIFI.ZipCodePhone, @"^\d+$");
               if (valPhone == false || valZip == false)
               {
                   strReturnMessage = "A 10 digit phone number and 5 digit zipcode are required.";
               }
               else if (objClsCheckLegacyWIFI.ZipCodePhone.Length != 5)
               {
                   strReturnMessage = "A 10 digit phone number and 5 digit zipcode are required.";
               }
               else if (objClsCheckLegacyWIFI.PhoneNumber == "")
               {
                   strReturnMessage = "A 10 digit phone number and 5 digit zipcode are required.";
               }


           }

			else if (objClsCheckLegacyWIFI.AccountNumber != "")
			{
				bool val = Regex.IsMatch(objClsCheckLegacyWIFI.AccountNumber, @"^\d+$");
                bool valZip = Regex.IsMatch(objClsCheckLegacyWIFI.ZipCodeAccount, @"^\d+$");
                if (val == false || valZip == false)
				{
                    strReturnMessage = "A 16 digit account number and 5 digit Zipcode are required.";
				}
				else if (objClsCheckLegacyWIFI.AccountNumber.Length != 16)
				{
                    strReturnMessage = "A 16 digit account number and 5 digit Zipcode are required.";
				}
                else if (objClsCheckLegacyWIFI.ZipCodeAccount=="")
                {
                    strReturnMessage = "A 16 digit account number and 5 digit Zipcode are required.";
                }
                else if (objClsCheckLegacyWIFI.ZipCodeAccount.Length != 5)
                {
                    strReturnMessage = "A 16 digit account number and 5 digit Zipcode are required.";
                }

			}
           else if (objClsCheckLegacyWIFI.ZipCodeAccount != "")
			{
               bool valAcc = Regex.IsMatch(objClsCheckLegacyWIFI.AccountNumber, @"^\d+$");
               bool valZip = Regex.IsMatch(objClsCheckLegacyWIFI.ZipCodeAccount, @"^\d+$");

               if (valAcc == false || valZip == false)
				{
                   strReturnMessage = "A 16 digit account number and 5 digit Zipcode are required.";
				}
               else if (objClsCheckLegacyWIFI.ZipCodePhone.Length != 5)
				{
                   strReturnMessage = "A 16 digit account number and 5 digit Zipcode are required.";
				}
               else if (objClsCheckLegacyWIFI.AccountNumber == "")
			{
                   strReturnMessage = "A 16 digit account number and 5 digit Zipcode are required.";
				}
               else if (objClsCheckLegacyWIFI.ZipCodeAccount == "")
				{
                   strReturnMessage = "A 16 digit account number and 5 digit Zipcode are required.";
				}
			}

            
			return strReturnMessage;
		}

		// Execute when user entered only Mac Address
		private string GetEligibilityStatussMAC(ClsCheckLegacyWIFI objClsCheckLegacyWIFI)
		{
			int rowcount = 0;
			string returnMsg = string.Empty;

			SqlConnection sqlConn = GetConectionString();

			try
			{
				SqlCommand sqlCmd = new SqlCommand();
				sqlCmd.CommandText = "PROC_GET_UPDATE_FIRMWARE_MACADDR";
				sqlCmd.CommandType = CommandType.StoredProcedure;
				sqlCmd.Connection = sqlConn;
				sqlCmd.Parameters.AddWithValue("@MAC_ADDR", objClsCheckLegacyWIFI.MacAddress.Trim().Replace("'", "''").ToString());
				sqlConn.Open();
				rowcount = (int)sqlCmd.ExecuteScalar();
				sqlConn.Close();
				if (rowcount > 0)
				{
                    //returnMsg = "Your device is eligible for a firmware upgrade.";
				}
				else
				{
					returnMsg = "Your device does not require an update at this time.";
				}
			}
			catch (Exception ex)
			{
				returnMsg = ex.Message + ex.Source;
			}
			finally
			{
				if (sqlConn.State.Equals(ConnectionState.Open))
					sqlConn.Close();
				}

			return returnMsg;
		}

		// Execute when user entered only Zipcode or Account Number
		private string GetEligibilityStatussZIPAcc(ClsCheckLegacyWIFI objClsCheckLegacyWIFI)
		{
			int rowcount = 0;
			string returnMsg = string.Empty;
			SqlConnection sqlConn = new SqlConnection();
			sqlConn = GetConectionString();

			try
			{
				SqlCommand sqlCmd = new SqlCommand();
				sqlCmd.CommandText = "PROC_GET_UPDATE_FIRMWARE_ACC_ZIP";
				sqlCmd.CommandType = CommandType.StoredProcedure;
				sqlCmd.Connection = sqlConn;
				sqlCmd.Parameters.AddWithValue("@ACCOUNT_NUM", objClsCheckLegacyWIFI.AccountNumber.Trim().Replace("'", "''").ToString());
                sqlCmd.Parameters.AddWithValue("@ZIPCODE", objClsCheckLegacyWIFI.ZipCodeAccount.Trim().Replace("'", "''").ToString());
				sqlConn.Open();
				rowcount = (int)sqlCmd.ExecuteScalar();
				sqlConn.Close();
				if (rowcount > 0)
				{
                    //returnMsg = "Your device is eligible for a firmware upgrade.";
				}
				else
				{
					returnMsg = "Your device does not require an update at this time.";
				}
			}
			catch (Exception ex)
			{
				returnMsg = ex.Message + ex.Source;
			}
			finally
			{
				if (sqlConn.State.Equals(ConnectionState.Open))
					sqlConn.Close();
				}

			return returnMsg;
		}

		// Execute when user entered only Zipcode or Phone Number
		private string GetEligibilityStatussZipPhone(ClsCheckLegacyWIFI objClsCheckLegacyWIFI)
		{
			int rowcount = 0;
			string returnMsg = string.Empty;

			SqlConnection sqlConn = GetConectionString();

			try
			{
				SqlCommand sqlCmd = new SqlCommand();
				sqlCmd.CommandText = "PROC_GET_UPDATE_FIRMWARE_ZIP_PHONE";
				sqlCmd.CommandType = CommandType.StoredProcedure;
				sqlCmd.Connection = sqlConn;
                sqlCmd.Parameters.AddWithValue("@ZIPCODE", objClsCheckLegacyWIFI.ZipCodePhone.Trim().Replace("'", "''").ToString());
                sqlCmd.Parameters.AddWithValue("@PHONE_NUM", objClsCheckLegacyWIFI.PhoneNumber.Trim().Replace("'", "''").ToString().Replace("-",""));
				sqlConn.Open();
				rowcount = (int)sqlCmd.ExecuteScalar();
				sqlConn.Close();
				if (rowcount > 0)
				{
                    //returnMsg = "Your device is eligible for a firmware upgrade.";
				}
				else
				{
					returnMsg = "Your device does not require an update at this time.";
				}
			}
			catch (Exception ex)
			{
				returnMsg = ex.Message + ex.Source;
			}
			finally
			{
				if (sqlConn.State.Equals(ConnectionState.Open))
					sqlConn.Close();
				}

			return returnMsg;
		}

        public static bool ValidatePhoneNumber(string phoneNumber)
        {
            return Regex.IsMatch(phoneNumber, "^[0-9][0-9]{2}[-]?[0-9]{3}[-]?[0-9]{4}$");
          
        }

		private SqlConnection GetConectionString()
		{
			// <add key="Charter.Website.WS.CommerceEngineConnectionString" value="Server=ignatz;Database=CharterDotcom;User ID=charter;Pwd=charter;"/>
			// <add key="Charter.Website.WS.CommerceEngineConnectionString" value="Server=CC2PRD;Database=CharterDotcom;User ID=charterdotcomdbo;Pwd=4kIeEon0;" />
			// <add key="Charter.Website.WS.CommerceEngineConnectionString" value="Server=CC2UAT;Database=CharterDotcom;User ID=charterdotcomdbo;Pwd=g28sy75T;" />
			// <add key="Charter.Website.WS.CommerceEngineConnectionString" value="Server=KSTLMSQL59;Database=CharterDotcom;User ID=charterdotcomdbo;Pwd=zYpYIpM0;"/>

			// <add key="Charter.Website.WS.CommerceEngineConnectionString" value="Server=KSTLMSQL59;Database=CharterDotcom;User ID=charterdotcomdbo;Pwd=zYpYIpM0;"/>
				
			// SqlConnection SqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["FirmwareDBConnection"].ConnectionString);
			// return SqlConn;
			// -----------------------------------------------------

			// var connectionString = ConfigurationSettings.AppSettings["Charter.Website.WS.CommerceEngineConnectionString"];
			string connectionString = ConfigurationSettings.AppSettings["Charter.Website.WS.CommerceEngineConnectionString"];

			//string connectionString = "Server=ignatz;Database=CharterDotcom;user id=charter;password=charter;";
			// string connectionString = @"Server=KSTLMSQL59;Database=CharterDotcom;user id=charterdotcomdbo;password=zYpYIpM0;";
			// string connectionString = @"Server=CC2UAT;Database=CharterDotcom;User ID=charterdotcomdbo;Pwd=g28sy75T;";

			// SqlConnection sqlConn = new SqlConnection(ConfigurationSettings.AppSettings["FirmwareDBConnection"]);

			SqlConnection sqlConn = new SqlConnection(connectionString);
			return sqlConn;
		}

		/*
				private SqlConnection GetConnectionString()
				{
					// string connectionString = "Server=ignatz;Database=CharterDotcom;user id=charter;password=charter;";
					string connectionString = @"Server=KSTLMSQL59;Database=CharterDotcom;user id=charterdotcomdbo;password=zYpYIpM0;";

					// SqlConnection sqlConn = new SqlConnection(ConfigurationSettings.AppSettings["FirmwareDBConnection"]);

					SqlConnection sqlConn = new SqlConnection(connectionString);
					return sqlConn;
				}
		*/

		#endregion
	}
	#endregion
}
