using System.Linq;
using TINK.Repository.Exception;
using TINK.MultilingualResources;

namespace TINK.Repository.Response
{
    public static class ResponseHelper
    {
        public const string RESPONSE_OK = "OK";

        /// <summary> Holds the description of the action logout. </summary>
        public const string BIKES_LOGOUT_ACTIONTEXT = "Abmeldung fehlgeschlagen.";

        /// <summary> Holds the description of the action get stations available. </summary>
        public const string STATIONS_AVAILABLE_ACTIONTEXT = "Abfrage der verfügbaren Stationen fehlgeschlagen.";

        /// <summary> Holds the description of the action get bikes available. </summary>
        public const string BIKES_AVAILABLE_ACTIONTEXT = "Abfrage der verfügbaren Fahrräder fehlgeschlagen.";

        /// <summary> Holds the description of the action get bikes occupied. </summary>
        public const string BIKES_OCCUPIED_ACTIONTEXT = "Abfrage der reservierten/ gebuchten Fahrräder fehlgeschlagen.";

        /// <summary> Holds the description of the action cancel reservation. </summary>
        public const string BIKES_CANCELREQUEST_ACTIONTEXT = "Aufheben der Reservierung fehlgeschlagen.";

        /// <summary> Holds the description of the action return bike. </summary>
        public const string BIKES_RETURNBIKE_ACTIONTEXT = "Rückgabe des Rads fehlgeschlagen.";

        /// <summary>
        /// Checks if log in response is ok.
        /// </summary>
        /// <param name="response">Response to check whether it is valid.</param>
        /// <param name="mail">Mail addess used to create details error message in case log in response is invalid.</param>
        /// <returns></returns>
        public static AuthorizationResponse GetIsResponseOk(this AuthorizationResponse response, string mail)
        {
            if (response == null)
            {
                throw new InvalidResponseException<AuthorizationResponse>("Anmeldung fehlgeschlagen.", null);
            }

            if (response.response_state.ToUpper() == InvalidAuthorizationResponseException.AUTH_FAILURE_STATUS_MESSAGE_UPPERCASE)
            {
                throw new InvalidAuthorizationResponseException(mail, response);
            }
            else if (!response.response_state.Trim().ToUpper().StartsWith(RESPONSE_OK))
            {
                throw new InvalidResponseException<AuthorizationResponse>($"Anmeldung {mail} fehlgeschlagen.\r\nServer Antwort: {response.response_text}", response);
            }

            return response;
        }

        /// <summary>
        /// Checks if log out response is ok.
        /// </summary>
        /// <param name="p_oResponse">Response to check whether it is valid.</param>
        /// <returns></returns>
        public static AuthorizationoutResponse GetIsResponseOk(this AuthorizationoutResponse p_oResponse)
        {   
            if (AuthcookieNotDefinedException.IsAuthcookieNotDefined(p_oResponse, BIKES_LOGOUT_ACTIONTEXT, out AuthcookieNotDefinedException exception))
            {
                throw exception;
            }

            GetIsResponseOk(p_oResponse, BIKES_LOGOUT_ACTIONTEXT);

            if (p_oResponse.authcookie != "1")
            {
                throw new InvalidResponseException<AuthorizationoutResponse>(
                    BIKES_LOGOUT_ACTIONTEXT, 
                    p_oResponse);
            }

            return p_oResponse;
        }

        /// <summary>Gets if a call to reserve bike succeeded or not by checking a booking response.</summary>
        /// <param name="bikeId">Id of bike which should be booked.</param>
        /// <param name="sessionCookie">Sessiong cookie of logged in user.</param>
        /// <param name="bookingResponse">Response to check.</param>
        /// <returns></returns>
        public static BikeInfoReservedOrBooked GetIsReserveResponseOk(
            this ReservationBookingResponse bookingResponse,
            string bikeId)
        {
            GetIsResponseOk(bookingResponse, string.Format(AppResources.ExceptionTextReservationBikeFailedGeneral, bikeId));

            if (BookingDeclinedException.IsBookingDeclined(bookingResponse.response_state, out BookingDeclinedException exception))
            {
                throw exception;
            }
            
            // Get bike which has to be booked.
            var bikeInfoRequestedOccupied = bookingResponse?.bikes_occupied?.Values?.FirstOrDefault(x => x.bike == bikeId);
            if (bikeInfoRequestedOccupied == null)
            {
                throw new System.Exception(string.Format(
                    AppResources.ExceptionTextReservationBikeFailedUnavailalbe,
                    bikeId,
                    !string.IsNullOrWhiteSpace(bookingResponse?.response_text) ? $"\r\n{bookingResponse.response_text}" : string.Empty));
            }

            return bikeInfoRequestedOccupied;
        }

        /// <summary> Gets if a booking call succeeded or not by checking a booking response. </summary>
        /// <param name="bikeId">Id of bike which should be booked.</param>
        /// <param name="bookingResponse">Response to check.</param>
        /// <returns></returns>
        public static BikeInfoReservedOrBooked GetIsBookingResponseOk(
            this ReservationBookingResponse bookingResponse,
            string bikeId)
        {
            GetIsResponseOk(bookingResponse, string.Format(AppResources.ExceptionTextRentingBikeFailedGeneral, bikeId));

            // Get bike which has to be booked.
            var bikeInfoRequestedOccupied = bookingResponse?.bikes_occupied?.Values?.FirstOrDefault(x => x.bike == bikeId);
            if (bikeInfoRequestedOccupied == null)
            {
                throw new System.Exception(string.Format(
                    AppResources.ExceptionTextRentingBikeFailedUnavailalbe,
                    bikeId,
                    !string.IsNullOrWhiteSpace(bookingResponse?.response_text) ? $"\r\n{bookingResponse.response_text}" : string.Empty));
            }

            return bikeInfoRequestedOccupied;
        }

        /// <summary> Gets if request is ok.</summary>
        /// <param name="response">Response to verify.</param>
        /// <param name="textOfAction">Text describing request which is shown if validation fails.</param>
        /// <returns>Verified response.</returns>
        public static T GetIsResponseOk<T>(this T response, string textOfAction)  where T : ResponseBase
        {
            if (response == null || response.response_state == null)
            {
                throw new InvalidResponseException<T>(textOfAction, null);
            }

            if (AuthcookieNotDefinedException.IsAuthcookieNotDefined(response, textOfAction, out AuthcookieNotDefinedException exception))
            {
                throw exception;
            }

            if (!response.response_state.Trim().ToUpper().StartsWith(RESPONSE_OK))
            {
                throw new InvalidResponseException<T>(
                    $"{textOfAction}\r\nServer Antwort: {response.response_text}",
                    response);
            }

            return response;
        }

        /// <summary> Gets if cancel or booking request is ok.</summary>
        /// <param name="cancelBookingResponse">Response to verify.</param>
        /// <param name="textOfAction">Text describing request which is shown if validation fails.</param>
        /// <param name="bikeId">Id of bike.</param>
        /// <returns>Verified response.</returns>
        public static ReservationCancelReturnResponse GetIsCancelReservationResponseOk(
            this ReservationCancelReturnResponse cancelBookingResponse,
            string bikeId)
        {
            GetIsResponseOk<ResponseBase>(cancelBookingResponse, BIKES_CANCELREQUEST_ACTIONTEXT);

            // Get bike which has to be booked.
            var l_oBikeInfo = cancelBookingResponse?.bikes_occupied?.Values?.FirstOrDefault(x => x.bike == bikeId);
            if (l_oBikeInfo != null)
            {
                throw new ReturnBikeException(
                    cancelBookingResponse,
                    $"{BIKES_CANCELREQUEST_ACTIONTEXT} Aufruf wurde erfolgreich ausgeführt, aber Rad ist noch in Liste der reservierten Räder enthalten.");
            }

            return cancelBookingResponse;
        }

        /// <summary> Gets if return bike request is ok.</summary>
        /// <param name="returnBikeResponse">Response to verify.</param>
        /// <param name="textOfAction">Text describing request which is shown if validation fails.</param>
        /// <param name="bikeId">Id of bike.</param>
        /// <returns>Verified response.</returns>
        public static ReservationCancelReturnResponse GetIsReturnBikeResponseOk(
            this ReservationCancelReturnResponse returnBikeResponse,
            string bikeId)
        {
            // Check if bike is at station.
            if (NotAtStationException.IsNotAtStation(returnBikeResponse.response_state.ToUpper(), out NotAtStationException notAtStationException))
            {
                throw notAtStationException;
            }

            // Check if GPS data was send to copri.
            if (NoGPSDataException.IsNoGPSData(returnBikeResponse.response_state.ToUpper(), out NoGPSDataException noGPSDataException))
            {
                throw noGPSDataException;
            }

            GetIsResponseOk<ResponseBase>(returnBikeResponse, BIKES_RETURNBIKE_ACTIONTEXT);

            // Get bike which has to be booked.
            var l_oBikeInfo = returnBikeResponse?.bikes_occupied?.Values?.FirstOrDefault(x => x.bike == bikeId);
            if (l_oBikeInfo != null)
            {
                throw new ReturnBikeException(
                    returnBikeResponse,
                    $"{BIKES_RETURNBIKE_ACTIONTEXT} Aufruf wurde erfolgreich ausgeführt, aber Rad ist noch in Liste der gemieteten Räder enthalten.");
            }

            return returnBikeResponse;
        }

        /// <summary>
        /// Gets the response for bikes occupied request with no bikes reserved.
        /// </summary>
        /// <param name="p_strSesstionCookie"></param>
        /// <returns></returns>
        public static BikesReservedOccupiedResponse GetBikesOccupiedNone(string p_strSesstionCookie = null)
        {
            var l_oJson = CopriCallsMonkeyStore.BIKESOCCUPIED.Replace(@"""authcookie"": """"", @"""authcookie"": """ + (p_strSesstionCookie ?? string.Empty) + @"""");
            return CopriCallsStatic.DeserializeResponse(@"{ ""shareejson"" : " + l_oJson + "}", (version) => new BikesReservedOccupiedResponse());
        }
    }
}