package com.appizipay

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
import com.facebook.react.bridge.*
import com.izipay.izipay_pw_sdk.data.model.AppearenceControlsPaymentIzipay
import com.izipay.izipay_pw_sdk.data.model.AppearencePaymentIzipay
import com.izipay.izipay_pw_sdk.data.model.AppearenceVisualSettingsPaymentIzipay
import com.izipay.izipay_pw_sdk.data.model.BillingPaymentIzipay
import com.izipay.izipay_pw_sdk.data.model.ConfigRequest
import com.izipay.izipay_pw_sdk.data.model.CustomThemePaymentIzipay
import com.izipay.izipay_pw_sdk.data.model.CyberSource
import com.izipay.izipay_pw_sdk.data.model.OrderPaymentIzipay
import com.izipay.izipay_pw_sdk.data.model.PayOption
import com.izipay.izipay_pw_sdk.data.model.ShippingPaymentIzipay
import com.izipay.izipay_pw_sdk.data.model.TokenPaymentIzipay
import com.izipay.izipay_pw_sdk.domain.model.PaymentResponse
import com.izipay.izipay_pw_sdk.eventbus.EventBus
import com.izipay.izipay_pw_sdk.ui.embedded.callback.PayCallback
import com.izipay.izipay_pw_sdk.ui.embedded.callback.PayManager
import com.izipay.izipay_pw_sdk.ui.embedded.container.PaymentsFragment
import com.izipay.izipay_pw_sdk.ui.embedded.container.PaymentsObject
import com.izipay.izipay_pw_sdk.ui.fullscreend.ContainerActivity


class IzipayModule(reactContext: ReactApplicationContext) :
    ReactContextBaseJavaModule(reactContext), ActivityEventListener, PayCallback {

    private lateinit var libraryManager: PayManager
    private lateinit var listPayMethod:ArrayList<PayOption>
    private var paymentPromise: Promise? = null
    private val PAYMENT_REQUEST_CODE = 1234
    private lateinit var currentActivityLocal : Activity
    override fun getName(): String {
        return "IzipayModule"
    }

    init {
        reactContext.addActivityEventListener(this)
    }

    @ReactMethod
    fun launch(valor: String, modo: String, metodos: ReadableArray, promise: Promise) {

        currentActivityLocal = currentActivity!!

        if (currentActivityLocal == null) {
            promise.reject("NO_ACTIVITY", "No hay una actividad activa.")
            return
        }

        paymentPromise = promise
        val timeStamp = System.currentTimeMillis().toString()
        libraryManager = PayManager()
        libraryManager.setCallback(this)

        listPayMethod = arrayListOf()
        for (i in 0 until metodos.size()) {
            if(metodos.getString(i) == "Yape"){
                listPayMethod.add(PayOption.YAPE)
            }
            if(metodos.getString(i) == "Tarjeta"){
                listPayMethod.add(PayOption.CARD)
            }
        }

        try {

                val request = ConfigRequest(
                "SBOX",
                "pay",
                "VErethUtraQuxas57wuMuquprADrAHAb",
                "DMKTL"+timeStamp,
                "4001834",
                "",
                OrderPaymentIzipay(
                    timeStamp, //ordernumber
                    "PEN",
                    "11.00",
                    listPayMethod,
                    "mobile",
                    "autorize",
                    "ejemplo01@gmail.com",
                    timeStamp, //timestamp
                ),
                TokenPaymentIzipay(""),
                BillingPaymentIzipay(
                    "Juan",
                    "Quispe",
                    "ejemplo01@gmail.com",
                    "930292619",
                    "Av. flores",
                    "Lima",
                    "Lima",
                    "PE",
                    "33065",
                    "DNI",
                    "55555555"
                ),
                ShippingPaymentIzipay(
                    "Juan",
                    "Quispe",
                    "ejemplo01@gmail.com",
                    "930292619",
                    "Av. Alamo",
                    "Lima",
                    "Lima",
                    "PE",
                    "33065",
                    "DNI",
                    "55555555"
                ), // not required
                AppearencePaymentIzipay(
                    "ESP",
                    AppearenceControlsPaymentIzipay(
                        true,
                        true,
                    ),
                    AppearenceVisualSettingsPaymentIzipay(
                        true
                    ),
                    "green", //green red black
                    CustomThemePaymentIzipay(
                        "#333399",
                        "#333399",
                        "#333399",
                    ),
                    ""
                ),
                ""
            )

            if(modo == "FULLSCREEN"){
                val intent = Intent(currentActivityLocal, ContainerActivity::class.java)
                intent.putExtra(ContainerActivity.REQUEST, request)
                currentActivityLocal.startActivityForResult(intent, PAYMENT_REQUEST_CODE)
            }else{
                /**
                 * Integración con Android - Paso 5.2
                 */

                if (currentActivityLocal is FragmentActivity) {
                    val bundle = Bundle().apply {
                        putSerializable("data", request)
                    }
                    val transaction = (currentActivityLocal as FragmentActivity).supportFragmentManager.beginTransaction()
                    var fragment = PaymentsObject.paymentsObject() as PaymentsFragment
                    fragment.arguments = bundle
                    fragment.payManager = libraryManager
                    transaction
                        .addToBackStack(null)
                        .add(R.id.fragment_container, fragment)
                        .commit()
                }
            }
        
        } catch (e: Exception) {
            promise.reject("ERROR_LAUNCHING", e.message)
        }
    }

    override fun onActivityResult(activity: Activity?, requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == PAYMENT_REQUEST_CODE && paymentPromise != null) {
            val signature = data?.getStringExtra(ContainerActivity.RESPONSESIGNTURE).orEmpty()
            val payload = data?.getStringExtra(ContainerActivity.RESPONSEPAYLOAD).orEmpty()

            val result: WritableMap = Arguments.createMap().apply {
                putString("status", if (resultCode == Activity.RESULT_OK) "success" else "cancelled")
                putString("signature", signature)
                putString("payload", payload)
            }

            paymentPromise?.resolve(result)
            paymentPromise = null
        }
    }

    override fun onNewIntent(intent: Intent?) {
        // No se usa
    }

    override fun onDataFromPayments(success: Boolean, pdata: PaymentResponse?, psignature:String?) {
        val result: WritableMap = Arguments.createMap().apply {
            putString("status", if (success) "success" else "cancelled")
            putString("signature", psignature)
            putString("payload", pdata.toString())
        }

        paymentPromise?.resolve(result)
        paymentPromise = null

        if (currentActivityLocal is FragmentActivity) {
            if ((currentActivityLocal as FragmentActivity).supportFragmentManager.backStackEntryCount > 0)
                (currentActivityLocal as FragmentActivity).supportFragmentManager.popBackStack()
        }
    }
}
