public static void MinusToSearchCount(AggregatorSetting aggregatorSetting)
 {
     lock (ThisLock)
     {
         aggregatorSetting.CurrentSearches--;
     }
 }
        private static string GetH2H(long cityCode, AggregatorSetting aggregatorSetting, Settings settings)
        {
            if (settings.LookupSettings.H2HToSearch.ContainsKey(cityCode))
                return settings.LookupSettings.H2HToSearch[cityCode];

            return aggregatorSetting.H2HDefault;
        }
 public static void AddToSearchCount(AggregatorSetting aggregatorSetting)
 {
     lock (ThisLock)
     {
         aggregatorSetting.CurrentSearches++;
     }
 }
        public static void GetTransfers(Dictionary<int, decimal> transfers, SuperAvailabilityResponse superAvailabilityResponse, AggregatorSetting aggregatorSetting)
        {
            var threads = new List<ThreadWorking>();
            foreach (var transfer in transfers)
            {
                var transfersRequestV3 = new TransfersRequestV3
                {
                    ClientType = 0,
                    ConfirmationLevel = 0,
                    ChildAge = superAvailabilityResponse.AvailabilityRequest.ChildAge,
                    NoOfAdults = superAvailabilityResponse.AvailabilityRequest.NoOfAdults,
                    NoOfChildren = superAvailabilityResponse.AvailabilityRequest.NoOfChildren,
                    SvcDateFrom = superAvailabilityResponse.AvailabilityRequest.SvcDate,
                    SvcDateTo = superAvailabilityResponse.AvailabilityRequest.SvcDate.AddDays(superAvailabilityResponse.AvailabilityRequest.Nites),
                    LocationID = transfer.Key
                };

                var thread = new ThreadWorking
                {
                    TransferSearch = new TransferSearch(transfersRequestV3, aggregatorSetting)
                };

                thread.Thread = new Thread(thread.TransferSearch.Search);
                thread.Thread.Start();
                threads.Add(thread);
            }

            // join up all the threads
            foreach (var threadWorking in threads)
            {
                threadWorking.Thread.Join();
                transfers[threadWorking.TransferSearch.Request.LocationID] = threadWorking.TransferSearch.CheapestTransferPrice;
            }
        }
        public static List<AggregatorSetting> GetAggregatorAuthentication(Settings settings)
        {
            var returnData = new List<AggregatorSetting>();

            // Create and open the connection in a using block. This
            // ensures that all resources will be closed and disposed
            // when the code exits.
            using (var connection = new SqlConnection(settings.DatabaseSettings.ReadConnectionString))
            {
                // Create the Command and Parameter objects.
                var command = new SqlCommand("dbo.spAuthenticationGetAll", connection) {CommandType = CommandType.StoredProcedure};

                // Open the connection in a try/catch block.
                try
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        var setting = new AggregatorSetting
                        {
                            Enabled = (bool)reader["Enabled"],
                            H2HDefault = (string)reader["H2HDefault"],
                            UserName = (string)reader["UserName"],
                            Password = (string)reader["Password"],
                            Id = (int)reader["Id"],
                            PtsPassword = (string)reader["PTSPassword"],
                            PtsUserName = (string)reader["PTSUserName"],
                            HotelConcurrentSearches = (int)reader["HotelConcurrentSearches"],
                            Tracker = (string)reader["Tracker"],
                            PtsNetwork = (string)reader["PtsNetwork"],
                            PtsTimeOut = (int)reader["PtsTimeOut"],
                            PtsUrl = (string)reader["PtsUrl"],
                        };
                        var featureCode = (string)reader["PtsFeatureCode"];
                        setting.PtsFeatureCode = featureCode.Contains(",") ? featureCode.Split(',') : new[] { featureCode };

                        returnData.Add(setting);
                    }
                    reader.Close();
                }
                catch (Exception ex)
                {
                    ErrorHelper.SendErrorEmail(ex, "Error getting GetAggregatorAuthentication", settings);
                }

                return returnData;
            }
        }
        public static bool CheckIfWeAreOkToSearch(AggregatorSetting aggregatorSetting, Settings settings)
        {
            AddToSearchCount(aggregatorSetting);

            lock (ThisLock)
            {
                if (aggregatorSetting.CurrentSearches > aggregatorSetting.HotelConcurrentSearches)
                {
                    ErrorHelper.SendErrorEmail(new Exception("Speed limit error"), "Too many searches was carried out: <br />Aggregator: " + aggregatorSetting.UserName + "<br />Current Searches: " + GetCurrentSearchCount(aggregatorSetting) + "<br />Maximum Searches: " + aggregatorSetting.HotelConcurrentSearches, settings);
                    return false;
                }
            }

            return true;
        }
        public static TransfersResponseV3 Search(TransfersRequestV3 request, AggregatorSetting aggregatorSetting)
        {
            var authSoapHd = new AuthSoapHd
            {
                strUserName = aggregatorSetting.PtsUserName,
                strNetwork = aggregatorSetting.PtsNetwork,
                strPassword = aggregatorSetting.PtsPassword,
                strUserRef = "",
                strCustomerIP = "" //HttpContext.Current == null ? String.Empty : (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]).Split(',')[0].Trim()
            };

            var service = new AccommodationService { Url = aggregatorSetting.PtsUrl, AuthSoapHdValue = authSoapHd, Timeout = aggregatorSetting.PtsTimeOut };
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            TransfersResponseV3 response =  service.GetTransfersV3(request);
            stopwatch.Stop();

            return response;
        }
        /// <summary>
        /// </summary>
        /// <param name="request"></param>
        /// <param name="aggregatorSetting"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        private static AvailabilityRequest GetRequest(AccommodationSearchRequest request, AggregatorSetting aggregatorSetting, Settings settings)
        {
            var availabilityRequest = new AvailabilityRequest
            {
                HotelId = request.SuperIds == null ? null :  string.Join(",",  request.SuperIds),
                H2H = GetH2H(request.CityCode, aggregatorSetting, settings),
                FeatureCode = aggregatorSetting.PtsFeatureCode,
                DetailLevel = 5,
                CityCode = request.CityCode,
                ConfirmationLevel = 0
            };

            TimeSpan ts = request.CheckOut - request.CheckIn;
            availabilityRequest.Nites = (sbyte)ts.Days;
            availabilityRequest.SvcDate = request.CheckIn;
            availabilityRequest.NoOfAdults = (sbyte)request.NumberOfAdults;
            availabilityRequest.NoOfChildren = (sbyte)(request.ChildAge == null ? 0 : request.ChildAge.Count + request.NumberOfInfants ?? 0);
            if (request.ResortCode.HasValue && request.ResortCode.Value > 0)
                availabilityRequest.Location = (int)request.ResortCode.Value;

            var ages = new List<sbyte>();

            if (request.ChildAge != null)
                foreach (var i in request.ChildAge)
                {
                    ages.Add((sbyte)i);
                }

            for (var i = 0; i < request.NumberOfInfants; i++)
            {
                ages.Add(1);
            }

            availabilityRequest.ChildAge = ages.ToArray();
            availabilityRequest.Units = (sbyte)request.NumberOfRooms;

            return availabilityRequest;
        }
        public static SuperAvailabilityResponse Search(AccommodationSearchRequest request, Settings settings, AggregatorSetting aggregatorSetting, out int searchTime)
        {
            var availabilityRequest = GetRequest(request, aggregatorSetting, settings);

            var authSoapHd = new AuthSoapHd
            {
                strUserName = aggregatorSetting.PtsUserName,
                strNetwork = aggregatorSetting.PtsNetwork,
                strPassword = aggregatorSetting.PtsPassword,
                strUserRef = "",
                strCustomerIP = "" //HttpContext.Current == null ? String.Empty : (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]).Split(',')[0].Trim()
            };

            //"http://172.16.200.174/Tritonroomswsdev/AccommodationServicev2.svc";
            var service = new  AccommodationService { Url = aggregatorSetting.PtsUrl, AuthSoapHdValue = authSoapHd, Timeout = aggregatorSetting.PtsTimeOut };
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            SuperAvailabilityResponse response =  service.GetSuperAvailability(availabilityRequest);
            stopwatch.Stop();
            searchTime = (int)stopwatch.ElapsedMilliseconds;

            return response;
        }
        public void ConvertSearch(AccommodationSearchRequest request, AggregatorSetting aggregatorSetting)
        {
            Tracker = aggregatorSetting.Tracker;
            NumberOfRooms = request.NumberOfRooms;
            NumberOfAdults = request.NumberOfAdults;
            NumberOfChildren = request.ChildAge == null ? 0 : request.ChildAge.Count;
            NumberOfInfants = request.NumberOfInfants ?? 0;
            if (request.ChildAge != null)
            {
                var isFirst = true;
                foreach (var childAge in request.ChildAge)
                {
                    if (isFirst)
                        isFirst = false;
                    else
                        ChildAges += ",";

                    ChildAges += childAge;
                }
            }
            MinStarRating = request.MinStarRating;
            CheckIn = request.CheckIn;
            CheckOut = request.CheckOut;
            CountryCode = request.CountryCode;
            CityCode = request.CityCode;
            ResortCode = request.ResortCode ?? 0;

            if (request.SuperIds != null && request.SuperIds.Count != 0)
            {
                var isFirst = true;
                foreach (var superId in request.SuperIds)
                {
                    if (isFirst)
                        isFirst = false;
                    else
                        SuperIds += ",";

                    SuperIds += superId;
                }
            }
        }
        public static AccommodationSearchResponse Process(Settings settings, SuperAvailabilityResponse superAvailabilityResponse, AggregatorSetting aggregatorSetting, string rooms)
        {
            if (superAvailabilityResponse == null)
            {
                return new AccommodationSearchResponse
                {
                    Message = new Message
                    {
                        Success = false,
                        Errors = new List<string> { "There was no Search results returned due to an error" }
                    },
                    Results = null,
                    SearchResultSetGuid = new Guid()
                };
            }
            var returnHotels = new List<AccommodationSearchResponseHotel>();

            var getTheIataFromCity =  (settings.LookupSettings.CityAsIata.ContainsKey((int) superAvailabilityResponse.AvailabilityRequest.CityCode) ?  settings.LookupSettings.CityAsIata[(int) superAvailabilityResponse.AvailabilityRequest.CityCode] : null) ?? "-1";
            var destinationMarkup = (settings.LookupSettings.DestinationMarkup.ContainsKey(getTheIataFromCity) ? settings.LookupSettings.DestinationMarkup[getTheIataFromCity] : null) ?? settings.LookupSettings.DestinationMarkup["-1"];

            var transfers = new Dictionary<int, decimal>();

            // loop through each hotel
            if (superAvailabilityResponse.SuperHotelAvailabilityDetail != null)
            {
                if (aggregatorSetting.UserName.ToLower() == "tripadvisor")
                {
                    // loop through the hotels and see if there are any compulsory
                    foreach (var hotel in superAvailabilityResponse.SuperHotelAvailabilityDetail)
                    {
                        foreach (var room in hotel.Hotels)
                        {
                            if (room.TransferCompulsory && room.HotelLocationID.HasValue && !transfers.ContainsKey(room.HotelLocationID.Value))
                            {
                                transfers.Add(room.HotelLocationID.Value, -1);
                            }
                        }
                    }

                    TransferService.GetTransfers(transfers, superAvailabilityResponse, aggregatorSetting);
                }

                foreach (var hotel in superAvailabilityResponse.SuperHotelAvailabilityDetail)
                {
                    int star;
                    if (!string.IsNullOrEmpty(hotel.SuperHotelCategory) && int.TryParse(hotel.SuperHotelCategory.Substring(0, 1), out star))
                    {
                        // do nothing
                    }
                    else
                        star = 0;

                    // convert the hotel ready
                    var returnHotel = ConvertService.Convert(hotel, star);
                    var hotelId = int.Parse(hotel.SuperHotelID);
                    var hotelMarkups = settings.LookupSettings.HotelMarkup.ContainsKey(hotelId) ? settings.LookupSettings.HotelMarkup[hotelId] : null;

                    // loop through each room
                    foreach (var room in hotel.Hotels)
                    {
                        // see if we need to find out transfers

                        // hotel markup rules
                        if (hotelMarkups != null)
                        {
                            if (hotelMarkups.IsPercentageMarkup)
                                room.Price += (room.Price/100m)*hotelMarkups.Markup;
                            else
                                room.Price += hotelMarkups.Markup;
                        }
                        else
                        {
                            // now apply a destination markup
                            foreach (var markupDestination in destinationMarkup)
                            {
                                if (room.Price > markupDestination.MinPriceTakesEffect)
                                {
                                    if (markupDestination.IsPercentageMarkup)
                                        room.Price += (room.Price / 100m) * markupDestination.Markup;
                                    else
                                        room.Price += markupDestination.Markup;
                                    break;
                                }
                            }
                        }

                        // apply transfers if needed
                        //if (room.HotelLocationID.HasValue && room.TransferCompulsory && transfers.ContainsKey(room.HotelLocationID.Value))
                        //{
                        //    if (transfers[room.HotelLocationID.Value] == -1)
                        //        continue;
                        //    room.MarkupTotals.FixedTotal += transfers[room.HotelLocationID.Value];/}

                        // round the price off
                        room.Price = Math.Round(room.Price, 2);

                        // convert to the object to return
                        returnHotel.Rooms.Add(ConvertService.Convert(room,  aggregatorSetting, hotel.SuperHotelID, rooms));
                    }

                    if (returnHotel.Rooms.Any())
                        returnHotels.Add(returnHotel);
                }
            }
            var returnResult = new AccommodationSearchResponse
            {
                Message = new Message
                {
                    Success = true
                },
                Results = returnHotels,
                SearchResultSetGuid = superAvailabilityResponse.ResultID == null ? new Guid() : new Guid(superAvailabilityResponse.ResultID)
            };

            return returnResult;
        }
 public static int GetCurrentSearchCount(AggregatorSetting aggregatorSetting)
 {
     return aggregatorSetting.CurrentSearches;
 }
 public TransferSearch(TransfersRequestV3 request, AggregatorSetting aggregatorSetting)
 {
     Request = request;
     AggregatorSetting = aggregatorSetting;
 }