using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using SepehrFlightApiSampleClient.BulkAvailability.WebApi;
using SepehrFlightApiSampleClient.BulkAvailability.WinForms.ClosedFlights.ViewModels;
using BulkAvailabilityApiModel = Sepehr.ApiGateway.Partners.Contracts.Flight.BulkAvailability.V17;

namespace SepehrFlightApiSampleClient.BulkAvailability.WinForms.ClosedFlights
{
    public partial class BulkClosedFlightsForm : Form
    {
        private readonly MainForm _mainForm;
        private List<BulkAvailabilityApiModel.GetClosedFlights.ResponseModel.ClosedFlight> _closedFlightList = new List<BulkAvailabilityApiModel.GetClosedFlights.ResponseModel.ClosedFlight>();

        public BulkClosedFlightsForm(MainForm mainForm)
        {
            _mainForm = mainForm;
            InitializeComponent();

            dtpToDate.Value = DateTime.Now.AddYears(1);
        }

        private void btnGetDifferentially_Click(object sender, EventArgs e)
        {
            try
            {
                var watch = Stopwatch.StartNew();

                ClearUiObjects();

                _closedFlightList = new List<BulkAvailabilityApiModel.GetClosedFlights.ResponseModel.ClosedFlight>();


                GetClosedFlightsFromApi();


                Application.DoEvents();

                watch.Stop();

                DataBindFlightGrid();

                MessageBox.Show(
                    $@"{gridFlightList.Rows.Count} closed flights{Environment.NewLine}{watch.Elapsed.TotalSeconds} seconds{Environment.NewLine}Done");

            }
            finally
            {
                btnGet.Enabled = true;
            }
        }

        private void ClearUiObjects()
        {
            btnGet.Enabled = false;
            gridFlightList.DataSource = null;
            gridFlightList.Refresh();
        }

        private void GetClosedFlightsFromApi()
        {
            var charterRequest = new BulkAvailabilityApiModel.GetClosedFlights.RequestModel.Request
            {
                UserName = _mainForm.txtUsername.Text,
                Password = _mainForm.txtPassword.Text,
                FromDate = dtpFromDate.Value.ToString("yyyy-MM-dd"),
                ToDate = dtpToDate.Value.ToString("yyyy-MM-dd"),
                Language = "FA",
                FetchFlightsThatAreNotOwnedBySupplier = chkFetchFlightsThatAreNotOwnedBySupplier.Checked
            };

            var charterResponse = GetClosedFlightsApi.Post(_mainForm.txtUrl.Text, charterRequest);
            _closedFlightList.AddRange(charterResponse.ClosedFlightList);
        }

        private BindingSource _bnsFlights;
        private void DataBindFlightGrid()
        {
            _bnsFlights = new BindingSource();

            var allFlightsViewModel = _closedFlightList
                .Select(f => new Flight(f));

            if (!string.IsNullOrEmpty(txtFlightNumberFilter.Text))
            {
                allFlightsViewModel = allFlightsViewModel
                    .Where(f => f.FlightNumber.Contains(txtFlightNumberFilter.Text));
            }

            if (!string.IsNullOrEmpty(txtOriginFilter.Text))
            {
                allFlightsViewModel = allFlightsViewModel
                    .Where(f => f.Origin == txtOriginFilter.Text);
            }

            if (!string.IsNullOrEmpty(txtDestinationFilter.Text))
            {
                allFlightsViewModel = allFlightsViewModel
                    .Where(f => f.Destination == txtDestinationFilter.Text);
            }

            if (!string.IsNullOrEmpty(txtFilterShamsiFlightDate.Text))
            {
                allFlightsViewModel = allFlightsViewModel
                    .Where(f => f.ShamsiDepartureDateTime.Contains(txtFilterShamsiFlightDate.Text));
            }

            allFlightsViewModel = allFlightsViewModel
                .OrderBy(f => f.DepartureDateTime);

            _bnsFlights.DataSource = allFlightsViewModel.ToList();

            gridFlightList.DataSource = _bnsFlights;
        }

        private void gridFlightList_SelectionChanged(object sender, EventArgs e)
        {
            if (_bnsFlights.Current == null) return;

            var flightSegment = GetCurrentFlightFromGrid();

            if (flightSegment.Stop1 || flightSegment.Stop2)
            {
                btnShowStopInfo.Visible = true;
            }
            else
            {
                btnShowStopInfo.Visible = false;
            }
        }

        public Flight GetCurrentFlightFromGrid()
        {
            return (Flight)_bnsFlights?.Current;
        }

        private void txtFlightNumberFilter_TextChanged(object sender, EventArgs e)
        {
            DataBindFlightGrid();
        }

        private void txtFilterShamsiFlightDate_TextChanged(object sender, EventArgs e)
        {
            DataBindFlightGrid();
        }

        private void txtOriginFilter_TextChanged(object sender, EventArgs e)
        {
            DataBindFlightGrid();
        }

        private void txtDestinationFilter_TextChanged(object sender, EventArgs e)
        {
            DataBindFlightGrid();
        }

        private void btnShowStopInfo_Click(object sender, EventArgs e)
        {
            var flightSegment = GetCurrentFlightFromGrid();

            MessageBox.Show(flightSegment.GetStopData());
        }
    }
}
