using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using SepehrFlightApiSampleClient.Refund.WebApi;
using RequestModel = Sepehr.ApiGateway.Partners.Contracts.Flight.Refund.V3.RetrieveBooking.RequestModel;
using ResponseModel = Sepehr.ApiGateway.Partners.Contracts.Flight.Refund.V3.RetrieveBooking.ResponseModel;

namespace SepehrFlightApiSampleClient.Refund.WinForms
{
    public partial class RetrieveBookingForm : Form
    {
        private readonly MainForm _mainform;
        private ResponseModel.Response _retrieveBookingResponse;

        public RetrieveBookingForm(MainForm mainform)
        {
            _mainform = mainform;
            InitializeComponent();

            dgvFlights.AutoGenerateColumns = true;

            var chkSelectSegment = new DataGridViewCheckBoxColumn
            {
                HeaderText = "",
                Name = "chkSelectSegment"
            };
            dgvFlights.Columns.Add(chkSelectSegment);
        }


        public List<SegmentGridViewModel> GetSelectedSegments()
        {
            var selectedPassengers = new List<SegmentGridViewModel>();
            foreach (DataGridViewRow row in dgvFlights.Rows)
            {
                var chk = (DataGridViewCheckBoxCell)row.Cells["chkSelectSegment"];

                if (Convert.ToBoolean(chk.Value) == false) continue;

                selectedPassengers.Add((SegmentGridViewModel)row.DataBoundItem);
            }

            return selectedPassengers;
        }

        private void btnRetrieveBooking_Click(object sender, EventArgs e)
        {
            var request = new RequestModel.Request
            {
                Credential = new RequestModel.Credential
                {
                    Username = _mainform.txtUsername.Text,
                    Password = _mainform.txtPassword.Text
                },
                Pnr = txtPnr.Text,
            };

            _retrieveBookingResponse = RetrieveBookingV3Api.Post(
                _mainform.txtUrl.Text, 
                request);

            bnsFlights.DataSource = ConvertApiModelToViewModel(_retrieveBookingResponse);

            SelectAllPassengersInGrid();
        }

        private static List<SegmentGridViewModel> ConvertApiModelToViewModel(ResponseModel.Response response)
        {
            var result = new List<SegmentGridViewModel>();

            response.Passengers.ForEach(p =>
            {
                p.SegemntList.ForEach(s =>
                {
                    result.Add(new SegmentGridViewModel
                    {
                        FirstName = p.FirstName,
                        LastName = p.LastName,
                        TicketNumber = s.TicketNumber,
                        FlightNumber = s.FlightNumber,
                        FlightDate = s.FlightDate,
                        Origin = s.OriginIataCode,
                        Destination = s.DestinationIataCode
                    });
                });
            });

            result = result
                .OrderBy(x => x.FlightNumber)
                .ThenBy(x => x.TicketNumber)
                .ToList();

            return result;
        }

        private void SelectAllPassengersInGrid()
        {
            var firstRecordFlightNumber = dgvFlights.Rows[0].Cells[nameof(SegmentGridViewModel.FlightNumber)].Value.ToString();

            foreach (DataGridViewRow row in dgvFlights.Rows)
            {
                var currentRowFlightNumber = row.Cells[nameof(SegmentGridViewModel.FlightNumber)].Value.ToString();

                //in IF ro neveshtim ke age reserve roundtrip bod, toye grid
                //segment haye marbot be ye parvaz be sorate default entekhab beshe.
                //chon age ham segmente raft va ham segmente bargasht entekhab beshe
                //toye marhale badi (GetPenalty) server ejaze bedast ovordane penalty
                //ro nemide. chon faghat zamani mishe penalty gereft ke segment ha roye
                //ye shomare parvaz bashan. va baraye ye reserve roundtrip 2 bar bayad
                //GetPenalty ro call kard. yebar vase lege raft va yebar vase lege bargasht
                if (currentRowFlightNumber == firstRecordFlightNumber)
                {
                    var chk = (DataGridViewCheckBoxCell)row.Cells["chkSelectSegment"];
                    chk.Value = true;
                }
            }
        }

        private void btnNextStep_Click(object sender, EventArgs e)
        {
            if (rdoPassengerPersonalReason.Checked)
            {
                _mainform.tabControlRefund.SelectedTab = _mainform.tbgRefundGetPenalty;
            }
            else if (rdoChangeFlightScheduleByAirline.Checked)
            {
                _mainform.tbgDoRefund.Controls.Clear();

                var form = new DoRefundForm(
                    mainForm: _mainform,
                    retrieveBookingForm: this,
                    passengerForRefundList: GetSelectedSegments()
                        .ConvertAll(selectedPassenger => new DoRefundForm.PassengerForRefund
                        {
                            TicketNumber = selectedPassenger.TicketNumber,
                            PenaltyAmountThatPassengerShouldPay = 0,
                        }),
                    refundReason: Sepehr.ApiGateway.Partners.Contracts.Flight.Refund.V3.DoRefund.RequestModel.RefundReason.FlightScheduleChangedByAirline);
                form.TopLevel = false;
                form.Parent = _mainform.tbgDoRefund;
                form.Show();

                _mainform.tabControlRefund.SelectedTab = _mainform.tbgDoRefund;
            }
            else
            {
                MessageBox.Show($"Please selected refund reason");
            }
        }
    }

    public class SegmentGridViewModel
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string TicketNumber { get; set; }

        public string FlightNumber { get; set; }

        public string FlightDate { get; set; }

        public string Origin { get; set; }

        public string Destination { get; set; }
    }
}
