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

namespace SepehrFlightApiSampleClient.Refund.WinForms
{
    public partial class GetPenaltyForm : Form
    {
        private readonly MainForm _mainForm;
        private readonly RetrieveBookingForm _retrieveBookingForm;
        private ResponseModel.Response _getPenaltyResponse;

        public GetPenaltyForm(
            MainForm mainForm,
            RetrieveBookingForm retrieveBookingForm)
        {
            _mainForm = mainForm;
            _retrieveBookingForm = retrieveBookingForm;
            InitializeComponent();
        }

        private void btnGetPenalty_Click(object sender, EventArgs e)
        {
            var selectedSegments = _retrieveBookingForm.GetSelectedSegments();

            var request = new RequestModel.Request
            {
                Credential = new RequestModel.Credential
                {
                    Username = _mainForm.txtUsername.Text,
                    Password = _mainForm.txtPassword.Text
                },
                Pnr = _retrieveBookingForm.txtPnr.Text,
                SegmentList = selectedSegments
                    .ConvertAll(c => new RequestModel.Segment
                    {
                        TicketNumber = c.TicketNumber,
                    }),
            };

            _getPenaltyResponse = GetPenaltyApi.Post(_mainForm.txtUrl.Text, request);

            dgvPenalty.DataSource = _getPenaltyResponse.PassengerList;
            lblSumOfPenalyAmountThatPassengerShouldPay.Text = _getPenaltyResponse
                .PassengerList.Sum(x => x.PenaltyAmountThatPassengerShouldPay)
                .ToString("N2");
        }

        private void btnNextStep_Click(object sender, EventArgs e)
        {
            _mainForm.tbgRefund_DoRefund.Controls.Clear();

            var form = new DoRefundForm(
                mainForm: _mainForm,
                retrieveBookingForm: _retrieveBookingForm,
                passengerForRefundList: _getPenaltyResponse
                    .PassengerList
                    .ConvertAll(p => new DoRefundForm.PassengerForRefund
                    {
                        TicketNumber = p.TicketNumber,
                        PenaltyAmountThatPassengerShouldPay = p.PenaltyAmountThatPassengerShouldPay,
                    }),
                refundReason: Sepehr.ApiGateway.Partners.Contracts.Flight.Refund.V3.DoRefund.RequestModel.RefundReason.PassengerPersonalReason);
            form.TopLevel = false;
            form.Parent = _mainForm.tbgRefund_DoRefund;
            form.Show();

            _mainForm.tabControlRefund.SelectedTab = _mainForm.tbgRefund_DoRefund;
        }
    }
}
