using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using TaxProGST.API;
using TaxProGST.JsonModels;

namespace TaxProGSTApiWinFormsDemo
{
    public partial class frmGSTR1AApi : Form
    {
        GSTSession GstSession = new GSTSession();
        public frmGSTR1AApi()
        {
            try
            {
                InitializeComponent();

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void frmGSTR1AApi_Load(object sender, EventArgs e)
        {
            try
            {
                GstSession.ApiSetting = Shared.LoadAPISetting();
                GstSession.ApiLoginDetails = Shared.LoadAPILoginDetails();
                if(GstSession.ApiLoginDetails != null)
                {
                    txtGSTUserID.Text = GstSession.ApiLoginDetails?.GstPortalUserID ?? "";
                    txtGSTIN.Text = GstSession.ApiLoginDetails?.GSTIN ?? "";
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void btnBrowseGstr1AJson_Click(object sender, EventArgs e)
        {
            OpenFileDialog FileDialog = new OpenFileDialog();
            FileDialog.Filter = "GSTR-1A JSon Files (*.json)|*.json";  //Set filters
            FileDialog.FilterIndex = 1;          //Specify default filter
            if(FileDialog.ShowDialog() == DialogResult.Cancel)
                return;
            txtGSTR1Json.Text = FileDialog.FileName;
        }

        private void cboSignType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(cboSignType.Text == "EVC")
            {
                btnEVCOTP.Enabled = true;
                txtEVCOTP.ReadOnly = false;
            }
            else
            {
                btnEVCOTP.Enabled = false;
                txtEVCOTP.ReadOnly = true;
            }

        }

        private async void btnUploadData_Click(object sender, EventArgs e)
        {
            try
            {
                txtAPIResponse.Text = "Please wait...";
                await Task.Delay(200);
                if(string.IsNullOrEmpty(txtGSTR1Json.Text))
                    MessageBox.Show("GSTR-1 Json file path not provided");

                txtReferenceID.Text = "";
                lblRefID.Text = "";
                #region For Uploading using Json File
                string json = File.ReadAllText(txtGSTR1Json.Text);
                TxnRespWithTransAndRefID txnResp = await GSTR1AAPI.SaveGstr1AAsync(GstSession, txtReturnPeriod.Text, json);
                #endregion
                #region For Upload using object Example for B2B Only
                //Gstr1AJson gstr1A = new Gstr1AJson();
                //gstr1A.gstin = txtGSTIN.Text;
                //gstr1A.fp = txtReturnPeriod.Text;
                //gstr1A.gt = 0;//Gross Turnover
                //gstr1A.cur_gt = 0;//Current Gross Turnover
                //gstr1A.version = "GSTXXX";
                //gstr1A.hash = "hash";
                //gstr1A.b2b = new List<Gstr1AJson.B2b>();
                //Gstr1AJson.B2b B2BRecord = new Gstr1AJson.B2b();
                //B2BRecord.ctin = "27GSPMH0041G1ZZ";
                //B2BRecord.inv = new List<Gstr1AJson.B2b.Inv>();
                //Gstr1AJson.B2b.Inv B2bInv = new Gstr1AJson.B2b.Inv();
                //B2bInv.inum = "INV" + txtReturnPeriod.Text + "001";
                //B2bInv.idt = DateTime.ParseExact("01" + txtReturnPeriod.Text, "dd-mm-yyyy",  System.Globalization.CultureInfo.InvariantCulture);
                //B2bInv.val = 5900;
                //B2bInv.pos = "27";
                //B2bInv.rchrg = "N";
                //B2bInv.inv_typ = "R";
                //B2bInv.itms = new List<Gstr1AJson.B2b.Inv.Itm>();
                //Gstr1AJson.B2b.Inv.Itm B2BInvItem = new Gstr1AJson.B2b.Inv.Itm();
                //B2BInvItem.num = 1;
                //B2BInvItem.itm_det = new Gstr1AJson.B2b.Inv.Itm.ItmDet();
                //B2BInvItem.itm_det.rt = 18;
                //B2BInvItem.itm_det.txval = 5000;
                //B2BInvItem.itm_det.camt = 450;
                //B2BInvItem.itm_det.samt = 450;
                //B2BInvItem.itm_det.iamt = 0;
                //B2BInvItem.itm_det.csamt = 0;
                //B2bInv.itms.Add(B2BInvItem);
                //B2BRecord.inv.Add(B2bInv);
                //gstr1A.b2b.Add(B2BRecord);
                //TxnRespWithTransAndRefID txnResp = await GSTR1AAPI.SaveGstr1AAsync(GstSession, txtReturnPeriod.Text, gstr1);

                #endregion

                if(txnResp.IsSuccess)
                {
                    txtReferenceID.Text = txnResp.ReferenceID;
                    lblRefID.Text = txnResp.ReferenceID;
                }
                txtAPIResponse.Text = txnResp.TxnOutcome;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private async void btnCheckReturnStatus_Click(object sender, EventArgs e)
        {
            try
            {
                txtAPIResponse.Text = "Please wait...";
                await Task.Delay(200);
                TxnRespWithObj<Gstr1ReturnStatusJson> txnResp = await SharedAPI.GetReturnStatusAsync<Gstr1ReturnStatusJson>(GstSession, "GSTR1", txtGSTIN.Text, txtReturnPeriod.Text, lblRefID.Text, true);
                if(txnResp.IsSuccess)
                {
                    txtAPIResponse.Text = txnResp.TxnOutcome;
                    var errReport = txnResp.RespObj.error_report;
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private async void btnDownloadData_Click(object sender, EventArgs e)
        {
            try
            {
                txtAPIResponse.Text = "Please wait...";
                TxnRespWithObj<Gstr1AJson> txnResp = new TxnRespWithObj<Gstr1AJson>();
                string ApiAction = "";
                #region API Action 
                switch(cboSchedule.Text)
                {
                    case "B2B":
                        ApiAction = "R1AB2B";
                        break;
                    case "B2BA":
                        ApiAction = "R1AB2BA";
                        break;
                    case "B2CL":
                        ApiAction = "R1AB2CL";
                        break;
                    case "B2CLA":
                        ApiAction = "R1AB2CLA";
                        break;
                    case "B2CS":
                        ApiAction = "R1AB2CS";
                        break;
                    case "B2CSA":
                        ApiAction = "R1AB2CSA";
                        break;
                    case "NIL":
                        ApiAction = "R1ANIL";
                        break;
                    case "EXP":
                        ApiAction = "R1AEXP";
                        break;
                    case "EXPA":
                        ApiAction = "R1AEXPA";
                        break;
                    case "AT":
                        ApiAction = "ATR1A";
                        break;
                    case "ATA":
                        ApiAction = "ATAR1A";
                        break;
                    case "TXP":
                        ApiAction = "R1ATXP";
                        break;
                    case "TXPA":
                        ApiAction = "R1ATXPA";
                        break;
                    case "HSNSUM":
                        ApiAction = "R1AHSNSUM";
                        break;
                    case "CDNR":
                        ApiAction = "R1ACDNR";
                        break;
                    case "CDNRA":
                        ApiAction = "R1ACDNRA";
                        break;
                    case "CDNUR":
                        ApiAction = "R1ACDNUR";
                        break;
                    case "CDNURA":
                        ApiAction = "R1ACDNURA";
                        break;
                    case "DOCISS":
                        ApiAction = "R1ADOCISS";
                        break;
                    case "ECOM":
                        ApiAction = "R1AECOM";
                        break;
                    case "ECOMA":
                        ApiAction = "R1AECOMA";
                        break;
                    case "SUPECO":
                        ApiAction = "R1ASUPECO";
                        break;
                    case "SUPECOA":
                        ApiAction = "R1ASUPECOA";
                        break;
                    default:
                        break;
                }
                #endregion API Action
                txnResp = await GSTR1AAPI.GetGstr1ADataScheduleAsync(GstSession, ApiAction, "Get " + cboSchedule.Text + " Data", txtGSTIN.Text, txtReturnPeriod.Text, "", "", "", true);
                if(txnResp.IsSuccess)
                    txtAPIResponse.Text = JsonConvert.SerializeObject(txnResp.RespObj, Formatting.Indented);
                else
                    txtAPIResponse.Text = txnResp.TxnOutcome;


            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private async void btnDownloadSummary_Click(object sender, EventArgs e)
        {
            try
            {
                txtAPIResponse.Text = "Please wait...";

                #region Method1 to GetSummary
                TxnRespWithPayload txnResp = new TxnRespWithPayload();
                txnResp = await GSTR1AAPI.GetGstr1ASummaryPayloadAsync(GstSession, txtGSTIN.Text, txtReturnPeriod.Text, true);
                if(txnResp.IsSuccess && !string.IsNullOrEmpty(txnResp.ResponsePayload))
                    txtAPIResponse.Text = txnResp.ResponsePayload;
                else
                    txtAPIResponse.Text = txnResp.TxnOutcome;
                #endregion
                #region Or Method2 to GetSummary
                //TxnRespWithObj<GSTR1AReturnJson> txnResp = new TxnRespWithObj<GSTR1AReturnJson>();
                //txnResp = await GSTR1AAPI.GetGstr1ASummaryAsync(GstSession, txtGSTIN.Text, txtReturnPeriod.Text , true);
                //txtAPIResponse.Text = txnResp.TxnOutcome;
                #endregion

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private async void btnEVCOTP_Click(object sender, EventArgs e)
        {
            try
            {
                txtAPIResponse.Text = "Please wait...";
                TxnRespWithRefAck txnResp = await AuthAPI.GetEVCOTPAsync(GstSession, txtGSTIN.Text, "R1", txtPAN.Text);
                if(txnResp.IsSuccess)
                    txtAPIResponse.Text = "EVC OTP Send Successfully on Registered Mobile and Email";
                else
                    txtAPIResponse.Text = "Failed : Response - " + txnResp.TxnOutcome;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private async void btnFileReturn_Click(object sender, EventArgs e)
        {
            try
            {
                txtAPIResponse.Text = "Please wait...";
                TxnRespWithPayload txnResp;
                TxnRespWithRefAck txtRespWithARN = new TxnRespWithRefAck();
                string strResponsePayload = "";
                txnResp = await GSTR1AAPI.GetGstr1ASummaryPayloadAsync(GstSession, txtGSTIN.Text, txtReturnPeriod.Text, true);
                if(txnResp.IsSuccess && !string.IsNullOrEmpty(txnResp.ResponsePayload))
                {
                    strResponsePayload = txnResp.ResponsePayload;
                    txtRespWithARN = await GSTR1AAPI.FileGstr1AWithPayloadAsync(GstSession, txtReturnPeriod.Text, strResponsePayload, cboSignType.Text, txtPAN.Text, true, txtEVCOTP.Text);
                    txtAPIResponse.Text = txtRespWithARN.TxnOutcome;
                }
                else
                    txtAPIResponse.Text = txnResp.TxnOutcome;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private async void btnReset_Click(object sender, EventArgs e)
        {
            try
            {
                txtAPIResponse.Text = "Please wait...";
                await Task.Delay(200);
                txtReferenceID.Text = "";
                lblRefID.Text = "";
                TxnRespWithRefID txnResp = await GSTR1AAPI.ResetGstr1AAsync(GstSession, txtGSTIN.Text, txtReturnPeriod.Text);
                if(txnResp.IsSuccess)
                {
                    txtReferenceID.Text = txnResp.ReferenceID;
                    lblRefID.Text = txnResp.ReferenceID;
                }
                txtAPIResponse.Text = txnResp.TxnOutcome;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }



        private async void btnGenerateSummary_Click(object sender, EventArgs e)
        {
            try
            {
                txtAPIResponse.Text = "Please wait...";
                SubmitGSTR jGSTR = new SubmitGSTR();
                jGSTR.gstin = txtGSTIN.Text;
                jGSTR.ret_period = txtReturnPeriod.Text;
                //For Generating Summary below is mandatory. If this will not pass then instead of Generate Summary Return will be Submitted.
                //Use this carefully
                jGSTR.generate_summary = "Y";
                TxnRespWithTransAndRefID txnResp = await SharedAPI.SubmitGSTRReturnWithRefIdAsync(GstSession, "GSTR1", txtReturnPeriod.Text, jGSTR, true);
                if(txnResp.IsSuccess)
                {
                    txtReferenceID.Text = txnResp.ReferenceID;
                    lblRefID.Text = txnResp.ReferenceID;
                }
                txtAPIResponse.Text = txnResp.TxnOutcome;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private async void btnProceedToFileOrGenerateSummary_Click(object sender, EventArgs e)
        {
            try
            {
                //GSTR1 version 3.0 APIs have been updated. In this release Submit API will be replaced with Proceed to file (PTF). 
                //Now, on calling the Procced to File API , summary for that return period will be generated. 
                //Unlike Submit where return period freezes after doing submit, after doing Proceed to File user is still allowed to save invoices 
                //and perform PTF again to generate latest summary.
                ////GSTR1 version 3.1 Updated for GSTR-1 Nil Return

                txtAPIResponse.Text = "Please wait...";
                SubmitGSTR jGSTR = new SubmitGSTR();
                jGSTR.gstin = txtGSTIN.Text;
                jGSTR.ret_period = txtReturnPeriod.Text;
                ///Pass below parameter for GSTR-1 Nil Return. In case of Nil Return No need to check Return Status of Ref. ID.
                //jGSTR.isnil = "Y";
                TxnRespWithTransAndRefID txnResp = await SharedAPI.ProceedToFileGSTRAsync(GstSession, "GSTR1", txtReturnPeriod.Text, jGSTR, true);
                if(txnResp.IsSuccess)
                {
                    txtReferenceID.Text = txnResp.ReferenceID;
                    lblRefID.Text = txnResp.ReferenceID;
                }
                txtAPIResponse.Text = txnResp.TxnOutcome;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


    }
}
