package com.checkout.standard_caheckoutDemo;

import static android.content.ContentValues.TAG;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.checkout.standard_checkout_kit.PZCheckout;
import com.checkout.standard_checkout_kit.model.PayRequest;
import com.checkout.standard_checkout_kit.model.PayResult;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Locale;

public class CheckoutActivity extends AppCompatActivity implements PZCheckout.WebCheckoutListener {

    public TextInputLayout tildescription, tilamount;
    public TextInputEditText etamount, etorderdescription;
    public String mtransactionid;
    public Float amount;
    private Button pay;

    public String customerIp;

    final PayRequest requestParameters = new PayRequest();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_checkout);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(true);
            getSupportActionBar().setTitle("Checkout");
        }

        tildescription = findViewById(R.id.tildescription);
        tilamount = findViewById(R.id.tilamount);

        etorderdescription = findViewById(R.id.edtTitleDescription);
        etamount = findViewById(R.id.edtTitleAmount);

        customerIp = getLocalIpAddress();
        pay = findViewById(R.id.btn_payNow);
        etorderdescription.addTextChangedListener(new MyTextWatcher(etorderdescription));
        etamount.addTextChangedListener(new MyTextWatcher(etamount));

        requestParameters.setMemberId("14691");
        requestParameters.setToType("TWPayz");
        requestParameters.setMemberKey("KsidL3VNx4rNaxPG9eYBNXNVmxlbZXvn");
        requestParameters.setOrderDescription("Testing Transaction");
        requestParameters.setCountry("IN");
        requestParameters.setCity("Mumbai");
        requestParameters.setState("MH");
        requestParameters.setPostCode("400064");
        requestParameters.setStreet("Malad");
        requestParameters.setTelnocc("91");
        requestParameters.setPhone("8668459089");
        requestParameters.setEmail("riya.patel@gmail.com");
        requestParameters.setPaymentBrand("");
        requestParameters.setPaymentMode("");
        requestParameters.setCurrency("GBP");
        requestParameters.setTerminalId("");
        requestParameters.setIpAddress(customerIp);
        requestParameters.setHostUrl("https://sandbox.twpayz.com/transaction/Checkout");

        pay.setOnClickListener(v ->  {
            if (!validateMemberId()) {
                return;
            } else {
                mtransactionid = String.valueOf(etorderdescription.getText());
                requestParameters.setMerchantTransactionId(mtransactionid);
            }

            if (!validateAmount()) {
                return;
            } else {
                amount = Float.parseFloat(String.valueOf(etamount.getText()));
                requestParameters.setAmount(String.format(Locale.US, "%.2f", amount));
            }
            submitForm();

        });
    }

    public void submitForm() {

        if (!validateMemberId()) {
            return;
        }
        if (!validateAmount()) {
            return;
        }

        PZCheckout.WebCheckoutListener webCheckoutListener = this;
        PZCheckout pzCheckout = new PZCheckout();
        pzCheckout.initPayment(CheckoutActivity.this, requestParameters,webCheckoutListener);
    }

    private boolean validateMemberId() {
        if (etorderdescription.getText().toString().trim().isEmpty()) {
            tildescription.setError(getString(R.string.error_msg_mail));
            requestFocus(etorderdescription);
            return false;
        } else {
            tildescription.setErrorEnabled(false);
        }
        return true;
    }

    private boolean validateAmount() {
        if (etamount.getText().toString().trim().isEmpty()) {
            tilamount.setError(getString(R.string.error_msg_amount));
            requestFocus(etamount);
            return false;
        } else {
            tilamount.setErrorEnabled(false);
        }
        return true;
    }

    private void requestFocus(View view) {
        if (view.requestFocus()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }


    @Override
    public void onTransactionSuccess(PayResult payResult) {
        Intent intent = new Intent(getApplicationContext(), PaymentSuccessActivity.class);
        intent.putExtra("result", payResult.toJsonString());
        startActivity(intent);

    }

    @Override
    public void onTransactionFail(PayResult payResult) {
        Intent intent = new Intent(getApplicationContext(), PaymentSuccessActivity.class);
        intent.putExtra("result", payResult.toJsonString());
        startActivity(intent);

    }

    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String ip = Formatter.formatIpAddress(inetAddress.hashCode());
                        Log.i(TAG, "***** IP="+ ip);
                        return ip;
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(TAG, ex.toString());
        }
        return null;
    }

    private static class MyTextWatcher implements TextWatcher {

        private View view;

        private MyTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @SuppressLint("NonConstantResourceId")
        public void afterTextChanged(Editable editable) {
        }
    }
}