using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

/// <summary>
/// Summary description for AirEpointSupport
/// </summary>
public class AirEpointSupport
{
    
    string xmlPath = ConfigurationManager.AppSettings["XmlPath"].ToString();
    string XmlResponse = ConfigurationManager.AppSettings["XmlResponse"].ToString();
    public AirEpointSupport()
    {

    }
    public int CheckSearchFlight(string CityFrom, string CityTo)
    {
        try
        {
            string DestinationFromValue = FindAirPortCode(CityFrom).Replace(")", "");
            string DestinationToValue = FindAirPortCode(CityTo).Replace(")", "");
            string DestinationFrom = FindAirPortCityName(CityFrom);
            string DestinationTo = FindAirPortCityName(CityTo);
            DataSet _dsAirPortDetail = GetAirPortDetails();
            var RESULT = from table1 in _dsAirPortDetail.Tables[0].AsEnumerable()
                         where table1.Field<string>("CityCode").Equals(DestinationFromValue)
                         select table1;
            DataTable dt = new DataTable();
            dt = RESULT.CopyToDataTable();
            var RESULT1 = from table1 in _dsAirPortDetail.Tables[0].AsEnumerable()
                          where table1.Field<string>("CityCode").Equals(DestinationToValue)
                          select table1;
            DataTable dt1 = new DataTable();
            dt = RESULT.CopyToDataTable();
            dt1 = RESULT.CopyToDataTable();
            if (dt.Rows.Count > 0 && dt.Rows.Count > 0)
            {
                return 1;
            }
            else
            {
                return 0;
            }

        }
        catch (Exception ex)
        {
            //Air_transaction_Cal.writeToLogFile("BookingProcess_DomesticInterNational.aspx-CheckSearchFlight()" + ex.Message.ToString(), Server.MapPath("~/Air_InternaltionalExceptionList"));
            return 0;
        }


    }
    public string FindAirPortCode(string AirPortDetail)
    {

        string[] AirPortCode = AirPortDetail.Split('(');
        return Convert.ToString(AirPortCode[1]);

    }
    public string FindAirPortCityName(string CityNamedetail)
    {

        string[] CityName = CityNamedetail.Split(',');
        return Convert.ToString(CityName[0]);

    }
    public DataSet GetAirPortDetails()
    {
        DataSet ds = new DataSet();
        try
        {
            string path = HttpContext.Current.Server.MapPath(xmlPath + "AirPort.xml");
            ds.ReadXml(path);
            return ds;
        }
        catch (Exception ex)
        {
            return ds;

        }
    }
    public static string ToUpperFirstLetter(string source)
    {
        if (string.IsNullOrEmpty(source))
            return string.Empty;
        char[] letters = source.ToCharArray();
        letters[0] = char.ToUpper(letters[0]);
        return new string(letters);
    }
    public string CheckSourceDestination(string From, string To)
    {
        string SearchType = "";
        try
        {
            DataSet ds = new DataSet();
            ds = GetAirPortDetails();
            string DestinationFromValue = FindAirPortCode(From).Replace(")", "");
            string DestinationToValue = FindAirPortCode(To).Replace(")", "");

            string FlightTypeFrom = (from table1 in ds.Tables[0].AsEnumerable()
                                     where table1.Field<string>("CityCode").Equals(DestinationFromValue)
                                     select table1.Field<string>("Type")).FirstOrDefault();
            string FlightTypeTo = (from table1 in ds.Tables[0].AsEnumerable()
                                   where table1.Field<string>("CityCode").Equals(DestinationToValue)
                                   select table1.Field<string>("Type")).FirstOrDefault();
            if ((FlightTypeFrom == "DOM") && (FlightTypeTo == "DOM"))
            {
                SearchType = "DOM";
            }
            else if ((FlightTypeFrom == "DOM") && (FlightTypeTo == "INAIR"))
            {
                SearchType = "INAIR";
            }
            else if ((FlightTypeFrom == "INAIR") && (FlightTypeTo == "DOM"))
            {
                SearchType = "SETO";
            }
            else if ((FlightTypeFrom == "INAIR") && (FlightTypeTo == "INAIR"))
            {
                SearchType = "SETO";
            }
        }
        catch (Exception ex)
        {
            return SearchType;
        }
        return SearchType;

    }
    public void WriteXmlLog(string XmlString, string FileName)
    {
        try
        {
            #region Create Xml folder to save xml file
            string cdate = DateTime.Now.ToString("yyy-MM-dd");
            string thisDir = HttpContext.Current.Server.MapPath(XmlResponse);
            string path = thisDir + "Xml_Req_Resp_" + cdate;

            if (!Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            path = path + "//" + FileName + "_" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss-fff") + ".xml";
            File.WriteAllText(path, XmlString);
            #endregion

        }
        catch (Exception ex)
        { }

    }
    public void WriteToLog(string LogMessage, string PageName, string MethodName)
    {
        string strLogMessage = string.Empty;
        StreamWriter swLog;
        string strLogFile = HttpContext.Current.Server.MapPath(XmlResponse) + "LogFile.txt";
        strLogMessage = string.Format("{0}: {1}- {2} - {3}", DateTime.Now, PageName, MethodName, LogMessage);
        if (!File.Exists(strLogFile))
        {
            swLog = new StreamWriter(strLogFile);
        }
        else
        {
            swLog = File.AppendText(strLogFile);
        }

        swLog.WriteLine(strLogMessage);
        swLog.WriteLine();
        swLog.Close();
    }
    public string CalculateDuration(string DepartDateTime, string ArrivalDateTime)
    {
        DateTime Depart = Convert.ToDateTime(DepartDateTime);
        DateTime Arrival = Convert.ToDateTime(ArrivalDateTime);


        if (Arrival.Hour < 12 && Depart.Hour > 12)
        {
            string duration = (Arrival.AddDays(1) - Depart).ToString();
            return duration.Split(':')[0] + "h " + duration.Split(':')[1] + "m";
        }

        else
        {

            string duration = (Arrival - Depart).ToString();
            return duration.Split(':')[0] + "h " + duration.Split(':')[1] + "m";

        }


    }
    public string sendRequestAndGetResponse_Arzoo(string url, string RequestData)
    {
        string response = "";
        try
        {
            PostSubmitter post = new PostSubmitter();
            string str_request = RequestData;
            post.Url = url;
            post.PostItems.Add("xmlRequest", str_request);
            post.Type = PostSubmitter.PostTypeEnum.Post;
            string result = string.Empty;
            return result = post.Post();
        }
        catch (Exception ex)
        {
            WriteToLog(ex.Message, "AirSupportMethod.cs", "sendRequestAndGetResponse_Arzoo()");
            return response;
        }
    }
    public DataSet GetAirLineDetails()
    {
        DataSet ds = new DataSet();
        try
        {
            string path = HttpContext.Current.Server.MapPath(xmlPath + "AirLine.xml");
            ds.ReadXml(path);
            return ds;
        }
        catch (Exception ex)
        {
            return ds;

        }
    }

    public string Generate_TID()
    {
        string new_tid = System.Guid.NewGuid().ToString();
        new_tid = new_tid.Replace("-", string.Empty).ToLower();
        new_tid = new_tid.Substring(0, 14).Replace("a", "1");
        new_tid = new_tid.Substring(0, 14).Replace("b", "2");
        new_tid = new_tid.Substring(0, 14).Replace("c", "3");
        new_tid = new_tid.Substring(0, 14).Replace("d", "4");
        new_tid = new_tid.Substring(0, 14).Replace("e", "5");
        new_tid = new_tid.Substring(0, 14).Replace("f", "6");
        new_tid = new_tid.Substring(0, 14).Replace("g", "7");
        new_tid = new_tid.Substring(0, 14).Replace("h", "8");
        new_tid = new_tid.Substring(0, 14).Replace("i", "9");
        new_tid = new_tid.Substring(0, 14).Replace("j", "0");
        new_tid = new_tid.Substring(0, 14).Replace("k", "1");
        new_tid = new_tid.Substring(0, 14).Replace("l", "2");
        new_tid = new_tid.Substring(0, 14).Replace("m", "3");
        new_tid = new_tid.Substring(0, 14).Replace("n", "4");
        new_tid = new_tid.Substring(0, 14).Replace("o", "5");
        new_tid = new_tid.Substring(0, 14).Replace("p", "0");
        new_tid = new_tid.Substring(0, 14).Replace("q", "9");
        new_tid = new_tid.Substring(0, 14).Replace("r", "8");
        new_tid = new_tid.Substring(0, 14).Replace("s", "7");
        new_tid = new_tid.Substring(0, 14).Replace("t", "6");
        new_tid = new_tid.Substring(0, 14).Replace("u", "5");
        new_tid = new_tid.Substring(0, 14).Replace("v", "4");
        new_tid = new_tid.Substring(0, 14).Replace("w", "3");
        new_tid = new_tid.Substring(0, 14).Replace("x", "2");
        new_tid = new_tid.Substring(0, 14).Replace("y", "1");
        new_tid = new_tid.Substring(0, 14).Replace("z", "0");

        if (new_tid[0] == '0')
        {
            string s = new_tid.Substring(1, new_tid.Length - 1);
            new_tid = "9" + s;
        }

        return new_tid;
    }

    public string getFlightType(string PartnerRefID,string HURL)
    {
        string Returnvalue = "";

        try
        {
            SqlParameter[] param = new SqlParameter[]
{
new SqlParameter("@PartnerRefID",PartnerRefID),
};
            Returnvalue = Convert.ToString(SqlHelper.ExecuteScaler(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "B2B_Air_GetFlightType", param));
        }
        catch (Exception ex)
        {
            return Returnvalue;
        }
        return Returnvalue;
    }
    public DataSet GetAirImageDetails()
    {
        DataSet ds = new DataSet();
        try
        {
            string path = HttpContext.Current.Server.MapPath(xmlPath + "AirLineImageDetail.xml");
            ds.ReadXml(path);
            return ds;
        }
        catch (Exception ex)
        {
            return ds;

        }
    }
    public decimal GetWalletAmount(int UserId)
    {
        decimal CurrentWalletBalance = 0;
        try
        {
            SqlParameter[] param = new SqlParameter[]
{
new SqlParameter("@UserId",UserId),
};
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "proc_GetWalletAmount", param);
            if (ds.Tables[0].Rows.Count > 0)
            {
                CurrentWalletBalance = Convert.ToDecimal(ds.Tables[0].Rows[0]["Amount"]);
            }
        }
        catch (Exception ex)
        {
            return CurrentWalletBalance;
        }
        return CurrentWalletBalance;
    }
    public static string GeneratePassword()
    {
        string characterSet = "0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();

        //The below code will select the random characters from the set
        //and then the array of these characters are passed to string 
        //constructor to make an alphanumeric string
        string randomCode = new string(
            Enumerable.Repeat(characterSet, 12)
                .Select(set => set[random.Next(set.Length)])
                .ToArray());
        return randomCode;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="ActualBaseFare">Base Fare(Chargeable)</param>
    /// <param name="Tax">Tax--> AirportTax (Chargeable)</param>
    /// <param name="STax">STax--> Service Tax(Chargeable)</param>
    /// <param name="TDiscount">Discount</param>
    /// <param name="TCharge">TCharge(NonChargeable)</param>
    /// <returns>0- BaseFare,1-AirportTax,2-Service Tax,3-Txn Fee,4-Final Booking Discount,5-Tmisc,6-total</returns>
    public decimal[] DomesticPrice(decimal ActualBaseFare, decimal Tax, decimal STax, decimal TDiscount, decimal TCharge)
    {
        decimal[] fares = new decimal[6];
        fares[0] = ActualBaseFare ;
        fares[1] = Tax;
        fares[2] = STax;
        fares[3] = TCharge;
        decimal tdsappliedoncompany = CalculateTDSValue(TDiscount,"DOM");
        fares[4] = TDiscount + TCharge  - tdsappliedoncompany;
       decimal totalfare = (fares[0] + fares[1] + fares[2] + fares[3])-fares[4];
       fares[5] = totalfare;
        return fares;
    }

    public decimal CalculateTDSValue(decimal Discount, string FlightType)
    {
        decimal TDSValue = 0;
        TDSValue = Math.Ceiling(((Discount * Convert.ToDecimal(10.0000)) / 100));
        //#region Commented by Lavi for fast processing
        //try
        //{
        //    if (Discount > 0)
        //    {
        //        DataSet ds = GetTDSValue(FlightType);
        //        if (FlightType == "DOM")
        //        {
        //            if (ds.Tables[0].Rows.Count > 0)
        //            {
        //                if (ds.Tables[0].Rows[0]["DOMTDSType"].ToString().ToUpper() == "P")
        //                {
        //                    TDSValue = Math.Ceiling(((Discount * Convert.ToDecimal(ds.Tables[0].Rows[0]["DOMTDS"])) / 100));
        //                }
        //                else if (ds.Tables[0].Rows[0]["DOMTDSType"].ToString().ToUpper() == "R")
        //                {
        //                    TDSValue = Convert.ToDecimal(ds.Tables[0].Rows[0]["DOMTDS"]);
        //                }
        //            }
        //            else
        //            {
        //                TDSValue = 0;
        //            }
        //        }
        //        else if (FlightType == "INAIR")
        //        {
        //            if (ds.Tables[0].Rows.Count > 0)
        //            {
        //                if (ds.Tables[0].Rows[0]["INAIRTDSType"].ToString().ToUpper() == "P")
        //                {
        //                    TDSValue = Math.Ceiling(((Discount * Convert.ToDecimal(ds.Tables[0].Rows[0]["INAIRTSD"])) / 100));
        //                }
        //                else if (ds.Tables[0].Rows[0]["INAIRTDSType"].ToString().ToUpper() == "R")
        //                {
        //                    TDSValue = Convert.ToDecimal(ds.Tables[0].Rows[0]["INAIRTSD"]);
        //                }
        //            }
        //            else
        //            {
        //                TDSValue = 0;
        //            }
        //        }
        //    }
        //    else
        //    {
        //        TDSValue = 0;
        //    }
        //}
        //catch (Exception ex)
        //{
        //    return 0;
        //}
        //#endregion
        return TDSValue;
    }
    public DataSet GetTDSValue(string FlightType)
    {
        DataSet ds = new DataSet();
        try
        {
            SqlParameter[] param = new SqlParameter[] 
            {
                new SqlParameter("@FlightType_TDS",FlightType),
            };
            ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "proc_GetTDS_Percent", param);
        }
        catch (Exception ex)
        {
            return ds;
        }
        return ds;
    }


    public string GetActiveVendorForService(string servicename)
    {
        SqlParameter[] param=new SqlParameter[]
        {
            new SqlParameter("@servicename",servicename)
        };
        DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "GetActiveVendorForService", param);
        if (ds.Tables.Count > 0)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                return Convert.ToString(ds.Tables[0].Rows[0][0]);
            }
            else
            {
                return "";
            }

        }
        else
        {
            return "";
        }
    }
    public decimal[] GetPGChargesAndServiceTax(string PaymentMode,decimal TicketPrice,string Type)
    {
        SqlParameter[] param = new SqlParameter[]
        {
            new SqlParameter("@paymenttype", PaymentMode),
             new SqlParameter("@type", Type)
        };
        DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "get_commercials", param);
        decimal PGcharge = Convert.ToDecimal(ds.Tables[0].Rows[0][0]);
        char PgChargeType = Convert.ToChar(ds.Tables[0].Rows[0][1]);
        if (PgChargeType == 'P')
        {
            PGcharge = (TicketPrice * PGcharge) / 100;
        }
        else
        {
            PGcharge = PGcharge;
        }

        decimal stax= Convert.ToDecimal(ds.Tables[0].Rows[0][2]);
        stax = (PGcharge * stax) / 100;
        return new decimal[] { PGcharge, stax }; 
    }

    public string getAPIProvider(string PartnerRefID, string HURL)
    {
        string Returnvalue = "";
       
        try
        {
            SqlParameter[] param = new SqlParameter[]
{
new SqlParameter("@PartnerRefID",PartnerRefID),
};
            Returnvalue = Convert.ToString(SqlHelper.ExecuteScaler(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "B2B_API_PPROVIDER", param));
        }
        catch (Exception ex)
        {
            return Returnvalue;
        }
        return Returnvalue;
    }


}
