using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using SepehrFlightApiSampleClient.RetrieveBooking.WebApi;
using RequestModel = Sepehr.ApiGateway.Partners.Contracts.Flight.RetrieveBooking.V3.GetHistory.RequestModel;
using ResponseModel = Sepehr.ApiGateway.Partners.Contracts.Flight.RetrieveBooking.V3.GetHistory.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();

            dgvSegmentList.AutoGenerateColumns = true;

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


        public List<SegmentGridViewModel> GetSelectedSegments()
        {
            var selectedPassengers = new List<SegmentGridViewModel>();
            foreach (DataGridViewRow row in dgvSegmentList.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
            {
                Username = _mainform.txtUsername.Text,
                Password = _mainform.txtPassword.Text,
                Pnr = txtPnr.Text,
            };

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

            bnsSegments.DataSource = ConvertApiModelToViewModel(_retrieveBookingResponse);

            SelectAllPassengersInGrid();
        }

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

            response.LastState.PassengerList.ForEach(p =>
            {
                p.SegmentList.ForEach(s =>
                {
                    result.Add(new SegmentGridViewModel
                    {
                        FirstName = p.FirstName,
                        LastName = p.LastName,
                        TicketNumber = s.LocalTicketNumber,
                        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 = dgvSegmentList.Rows[0].Cells[nameof(SegmentGridViewModel.FlightNumber)].Value.ToString();

            foreach (DataGridViewRow row in dgvSegmentList.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.tbgRefund_GetPenalty;
            }
            else if (rdoChangeFlightScheduleByAirline.Checked)
            {
                _mainform.tbgRefund_DoRefund.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.tbgRefund_DoRefund;
                form.Show();

                _mainform.tabControlRefund.SelectedTab = _mainform.tbgRefund_DoRefund;
            }
            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; }
    }
}
