using GMCabsDriverAssistant.Models;
using GMCabsDriverAssistant.Models.Rydo;
using GMCabsDriverAssistant.Services;
using GMCabsDriverAssistantSolution.Models.Rydo;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace GMCabsDriverAssistantSolution.ViewModels
{
    [QueryProperty(nameof(RideRequestJson), nameof(RideRequestJson))]
    public class StartRideViewModel : BaseViewModel
    {
        #region Fields
        private string rideRequestJson;
        private string passengerName;
        private bool isCorporate;
        private string fullDestinationAddress;
        private StartRideResponse startRideResponse;
        private int frameWidth;
        private bool stopOver = false;
        private bool noStopOver = false;
        private int index = 0;
        private double destinationCircleColorOpecity = 0.2;
        private string destinationStopLabelColorCode = "#BECEDA";
        private bool isStopOver = false;
        private bool isNoStopOver = false;
        StartRideRequestDto startRideRequestDto;
        Page _page;
        public string meterRunningStatus;
        private string locationSuburbName;
        private string startSuburb;
        private string pickUpDateTime;
        private string timerSeconds;
        public int seconds = 0;
        private bool visibleTrip;
        private bool isEndTripButtonVisible = true;
        private string startTimeOrEndLocation;
        #endregion

        #region Properties
        public List<StopoverLocations> StopoverLocations { get; }
        public ObservableCollection<StopoverLocations> StopoverLocationsList { get; }
        public Command OnPassengerCollectedClick { get; }
        public string RideRequestJson
        {
            get => rideRequestJson;
            set
            {
                rideRequestJson = value;
                ProcessRiding(value);
            }
        }
        public string PassengerName
        {
            get => passengerName;
            set => SetProperty(ref passengerName, value);
        }
        public bool IsCorporate
        {
            get => isCorporate;
            set => SetProperty(ref isCorporate, value);
        }
        public string FullDestinationAddress
        {
            get => fullDestinationAddress;
            set => SetProperty(ref fullDestinationAddress, value);
        }
        public bool StopOver
        {
            get => stopOver;
            set => SetProperty(ref stopOver, value);
        }
        public bool NoStopOver
        {
            get => noStopOver;
            set => SetProperty(ref noStopOver, value);
        }
        public bool IsStopOver
        {
            get => isStopOver;
            set => SetProperty(ref isStopOver, value);
        }
        public bool IsNoStopOver
        {
            get => isNoStopOver;
            set => SetProperty(ref isNoStopOver, value);
        }
        public int FrameWidth
        {
            get => frameWidth;
            set => SetProperty(ref frameWidth, value);
        }
        public double DestinationCircleColorOpecity
        {
            get => destinationCircleColorOpecity;
            set => SetProperty(ref destinationCircleColorOpecity, value);
        }
        public string DestinationStopLabelColorCode
        {
            get => destinationStopLabelColorCode;
            set => SetProperty(ref destinationStopLabelColorCode, value);
        }
        public string StartSuburb
        {
            get => startSuburb;
            set
            {
                SetProperty(ref startSuburb, value);
            }
        }
        public string PickUpDateTime
        {
            get => pickUpDateTime;
            set => SetProperty(ref pickUpDateTime, value);
        }
        public string TimerSeconds
        {
            get => timerSeconds;
            set => SetProperty(ref timerSeconds, value);
        }
        public bool VisibleTrip
        {
            get => visibleTrip;
            set => SetProperty(ref visibleTrip, value);
        }
        public bool IsEndTripButtonVisible
        {
            get => isEndTripButtonVisible;
            set => SetProperty(ref isEndTripButtonVisible, value);
        }
        public string StartTimeOrEndLocation
        {
            get => startTimeOrEndLocation;
            set => SetProperty(ref startTimeOrEndLocation, value);
        }
        public Command OnPassengerDroppedOffClick { get; }
        public Command onEndTripClick { get; }
        #endregion

        #region Constructor
        public StartRideViewModel(Page page)
        {
            Title = "Passenger Collected";
            StopoverLocations = new List<StopoverLocations>();
            StopoverLocationsList = new ObservableCollection<StopoverLocations>();
            OnPassengerCollectedClick = new Command(PassengerCollected);
            startRideRequestDto = new StartRideRequestDto();
            OnPassengerDroppedOffClick = new Command(PassengerDroppedOff);
            _page = page;
            meterRunningStatus = Preferences.Get("MeterRunningStatus", "");
            StartTimeOrEndLocation = "Start Time";
        }
        #endregion

        #region Methods 
        private async void ProcessRiding(string rideRequestJson)
        {
            string rydoAccessToken = Preferences.Get(EftposLoginResponse.RYDO_ACCESS_TOKEN, "");
            GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
            startRideRequestDto = JsonSerializer.Deserialize<StartRideRequestDto>(rideRequestJson);
            StartRideRequest startRideRequest = startRideRequestDto.startRideRequest;
            if (startRideRequest.DriverId == "")
            {
                await Shell.Current.GoToAsync("..");
            }
            startRideResponse = new StartRideResponse();
            startRideResponse = await gmCabsDriverService.StartRiding(startRideRequest, rydoAccessToken, startRideRequestDto.BookingId.ToString());
            if (startRideResponse.StatusCode == (int)HttpStatusCode.OK)
            {
                PassengerName = startRideResponse.PassengerName;
                IsCorporate = startRideResponse.IsCorporate;
                startRideResponse.DriverId = startRideRequest.DriverId;
                startRideResponse.BookingId = startRideRequestDto.BookingId;
                if (IsCorporate)
                {
                    FrameWidth = 310;
                }
                else
                {
                    FrameWidth = 370;
                }
                startRideResponse.FrameWidth = FrameWidth;
                FullDestinationAddress = startRideResponse.EndAddress + " " + startRideResponse.EndSuburb;
                var locations = new List<StopoverLocations>();

                //These below-mentioned commented out codes are witten for checking the lists of Stop Over Locations as a mock data
                //because of unable to fetch real stop over location data from the dev rydo booking page

                //locations.Add(new StopoverLocations
                //{
                //    Latitude = -32.63,
                //    Longitude = 151.55,
                //    Address = "1 Milson St",
                //    Suburb = "Charlestown",
                //    StopNumber = 1
                //});
                //locations.Add(new StopoverLocations
                //{
                //    Latitude = -36.17,
                //    Longitude = 144.66,
                //    Address = "1/1 Milson St",
                //    Suburb = "Charlestown",
                //    StopNumber = 2
                //});
                //locations.Add(new StopoverLocations
                //{
                //    Latitude = -36.17,
                //    Longitude = 144.66,
                //    Address = "1/1 Milson St",
                //    Suburb = "Charlestown",
                //    StopNumber = 3
                //});
                //locations.Add(new StopoverLocations
                //{
                //    Latitude = -36.17,
                //    Longitude = 144.66,
                //    Address = "1/1 Milson St",
                //    Suburb = "Charlestown",
                //    StopNumber = 2
                //});
                //locations.Add(new StopoverLocations
                //{
                //    Latitude = -36.17,
                //    Longitude = 144.66,
                //    Address = "1/1 Milson St",
                //    Suburb = "Charlestown",
                //    StopNumber = 2
                //});
                //locations.Add(new StopoverLocations
                //{
                //    Latitude = -36.17,
                //    Longitude = 144.66,
                //    Address = "1/1 Milson St",
                //    Suburb = "Charlestown",
                //    StopNumber = 2
                //});
                locations.Add(new StopoverLocations
                {
                    Latitude = startRideResponse.EndLatitude,
                    Longitude = startRideResponse.EndLongitude,
                    Address = startRideResponse.EndAddress,
                    Suburb = startRideResponse.EndSuburb,
                    StopNumber = startRideResponse.StopoverLocations.Count + 1
                });
                startRideResponse.StopoverLocations.AddRange(locations);
                if (startRideResponse.StopoverLocations.Count > 0)
                {
                    StopOver = true;
                    NoStopOver = false;
                    IsStopOver = true;
                    IsNoStopOver = false;
                    StopoverLocations.Clear();
                    foreach (var locationlists in startRideResponse.StopoverLocations)
                    {
                        StopoverLocations.Add(locationlists);
                    }
                    setPrimaryStopOverLocation(StopoverLocations);
                }
                else
                {
                    StopOver = false;
                    NoStopOver = true;
                    IsStopOver = false;
                    IsNoStopOver = true;
                }
                if (startRideResponse.FixedAmount != null)
                {
                    decimal amount = Convert.ToDecimal(startRideResponse.FixedAmount) / 100.0m;
                    amount = amount * 1.00m;
                    startRideResponse.FixedAmount = amount;
                }
            }
        }
        private void setPrimaryStopOverLocation(List<StopoverLocations> stopoverLocations)
        {
            StopoverLocationsList.Clear();
            int stopOverLocationCount = 1;
            foreach (var location in stopoverLocations)
            {
                if (stopOverLocationCount == stopoverLocations.Count)
                {
                    location.IsLineVisible = false;
                }
                location.LabelColor = "#BBB9B9";
                location.CircleColorOpecity = 0.2;
                StopoverLocationsList.Add(location);

                if (stopoverLocations.Count == 1)
                {
                    location.LabelColor = "Black";
                    location.CircleColorOpecity = 0.5;
                    IsStopOver = false;
                    IsNoStopOver = true;
                }

                stopOverLocationCount++;
            }
        }

        private void setStopOverLocation(List<StopoverLocations> stopoverLocations)
        {
            StopoverLocationsList.Clear();
            int stopoverLocationIndex = 0;
            foreach (var location in stopoverLocations)
            {
                if (stopoverLocationIndex == stopoverLocations.Count - 1)
                {
                    location.IsLineVisible = false;
                }

                if (stopoverLocationIndex == index)
                {
                    location.LabelColor = "Black";
                    location.CircleColorOpecity = 0.5;
                }
                else
                {
                    location.LabelColor = "#BBB9B9";
                    location.CircleColorOpecity = 0.2;
                }
                StopoverLocationsList.Add(location);
                stopoverLocationIndex++;
            }
        }

        private async void PassengerCollected()
        {
            int stop_number = StopoverLocationsList[index].StopNumber;
            string booking_id = startRideRequestDto.BookingId.ToString();
            string rydoAccessToken = Preferences.Get(EftposLoginResponse.RYDO_ACCESS_TOKEN, "");
            GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
            await gmCabsDriverService.NotifyStop(stop_number, rydoAccessToken, booking_id);
            int StopoverLocationsListCount = StopoverLocationsList.Count;
            setStopOverLocation(StopoverLocations);
            if (index == StopoverLocationsListCount - 1)
            {
                DestinationStopLabelColorCode = "Black";
                DestinationCircleColorOpecity = 0.5;
                IsStopOver = false;
                IsNoStopOver = true;
            }
            index = index + 1;
        }

        public async void PassengerDroppedOff()
        {
            //if (meterRunningStatus == "Stopped")
            //{
            //UpdateBookingStatus();
            //if (startRideResponse.PaymentMethodId == null && startRideResponse.FixedAmount == null)
            //{
            //    await _page.Navigation.PushAsync(new PassengerDroppedWithNoPaymentMethodIdNoFixedFareTablet(startRideResponse));
            //}
            //else if (startRideResponse.PaymentMethodId == null && startRideResponse.FixedAmount != null)
            //{
            //    await _page.Navigation.PushAsync(new PassengerDroppedWithNoPaymentMethodIdAndFixedFareTablet(startRideResponse));
            //}
            //else if (startRideResponse.PaymentMethodId != null && startRideResponse.FixedAmount != null)
            //{
            //    await _page.Navigation.PushAsync(new PassengerDroppedWithPaymentMethodIdAndFixedFareTablet(startRideResponse));
            //}
            //else if (startRideResponse.PaymentMethodId != null && startRideResponse.FixedAmount == null)
            //{
            //    await _page.Navigation.PushAsync(new PassengerDroppedWithPaymentMethodIdNoFixedFareTablet(startRideResponse));
            //}
            //}
            //else
            //{
            //    _page.Navigation.ShowPopup(new MeterTripStatusDialogPage(this._page, startRideResponse));
            //}
        }


        #endregion
    }
}
