package org.linphone.bluereach;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import org.linphone.R;
import org.linphone.rest.AsyncHttpResponse;
import org.linphone.rest.RestApis;
import org.linphone.utils.AppIntegers;
import org.linphone.utils.AppMethods;
import org.linphone.utils.AppStrings;
import org.linphone.utils.PinEntryView;
import org.linphone.utils.SessionManager;

public class OtpVerification extends AppCompatActivity implements View.OnClickListener, AsyncHttpResponse.AsyncHttpResponseListener {

    PinEntryView otp_pet;
    TextView otp_submit_tv, otp_resend_tv, otp_call_tv;
    private static final String TAG = "OtpVerification";
    //LinphoneAddress.TransportType transport;
    String phoneNumber = "";
    Intent intent;
    SessionManager sm;
    ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.otp_verification);

        initUI();

    }

    public void initUI() {

        sm = new SessionManager(this);
        intent = getIntent();
        phoneNumber = intent.getStringExtra(AppStrings.IntentData.phoneNumber);
        otp_pet = (PinEntryView) findViewById(R.id.otp_pet);
        otp_submit_tv = (TextView) findViewById(R.id.otp_submit_tv);
        otp_resend_tv = (TextView) findViewById(R.id.otp_resend_tv);
        otp_call_tv = (TextView) findViewById(R.id.otp_call_tv);

        //transport = LinphoneAddress.TransportType.LinphoneTransportUdp;

        /*getting whatever data enter in otp box*/
        otp_pet.setOnPinEnteredListener(new PinEntryView.OnPinEnteredListener() {
            @Override
            public void onPinEntered(String pin) {
                otp_pet.getText();
            }
        });
        otp_submit_tv.setOnClickListener(this);
        otp_resend_tv.setOnClickListener(this);

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.otp_submit_tv:

                /*validation & performing otp verification process */

                if (otp_pet.getText().toString().isEmpty()) {
                    AppMethods.alertWithOk(this, getResources().getString(R.string.enter_otp));
                } else {
                    otpVerficationApi();
                }
                break;
            case R.id.otp_resend_tv:

                /*perorming resend OTP action here*/

                resendOtpApi();
                break;
            case R.id.otp_call_tv:
                break;
        }
    }

    public void otpVerficationApi() {
        if (AppMethods.isConnectingToInternet(this)) {
            AsyncHttpResponse response = new AsyncHttpResponse(this, true);
            JSONObject jo = null;
            try {
                jo = new JSONObject();
                jo.put(AppStrings.InputParams.action, RestApis.verify_otp);

                JSONObject job = new JSONObject();
                job.put(AppStrings.InputParams.PhoneNumber, phoneNumber);
                job.put(AppStrings.InputParams.OTP, otp_pet.getText().toString());

                jo.put(AppStrings.InputParams.params, job);
            } catch (Exception e) {
                e.printStackTrace();
            }
            response.postJsonAsyncHttp(RestApis.url, RestApis.verify_otp, jo);
        } else {
            AppMethods.alertForNoInternet(this);
        }
    }

    public void resendOtpApi() {
        if (AppMethods.isConnectingToInternet(this)) {
            AsyncHttpResponse response = new AsyncHttpResponse(this, true);
            JSONObject jo = null;
            try {
                jo = new JSONObject();
                jo.put(AppStrings.InputParams.action, RestApis.resend_otp);

                JSONObject job = new JSONObject();
                job.put(AppStrings.InputParams.PhoneNumber, phoneNumber);

                jo.put(AppStrings.InputParams.params, job);
            } catch (Exception e) {
                e.printStackTrace();
            }
            response.postJsonAsyncHttp(RestApis.url, RestApis.resend_otp, jo);
        } else {
            AppMethods.alertForNoInternet(this);
        }
    }

    public void resendOtpResponse(String response) {
        try {
            JSONObject jo = new JSONObject(response);
            String Status = jo.optString(AppStrings.OutputParams.Status);
            String Message = jo.optString(AppStrings.OutputParams.Message);
            if (Status.equals(AppStrings.OutputParams.Success)) {
                String OTP = jo.optString(AppStrings.OutputParams.OTP);
                AppMethods.alertWithOk(this, Message);
            } else {
                AppMethods.alertWithOk(this, Message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void otpVerficationResponse(String response) {
        try {

            JSONObject jo = new JSONObject(response);
            String Status = jo.optString(AppStrings.OutputParams.Status);
            String Message = jo.optString(AppStrings.OutputParams.Message);
            if (Status.equals(AppStrings.OutputParams.Success)) {
                String userdetails = jo.optString(AppStrings.OutputParams.userdetails);
                JSONObject job = new JSONObject(userdetails);
                String OTP = job.optString(AppStrings.OutputParams.OTP);
                String FirstName = job.optString(AppStrings.OutputParams.FirstName);
                String LastName = job.optString(AppStrings.OutputParams.LastName);
                String EmailID = job.optString(AppStrings.OutputParams.EmailID);
                String PhoneNumber = job.optString(AppStrings.OutputParams.PhoneNumber);
                String Password = job.optString(AppStrings.OutputParams.Password);
                String userID = job.optString(AppStrings.OutputParams.userID);
                String OtpVerificationStatus = job.optString(AppStrings.OutputParams.OtpVerificationStatus);
                sm.setStoreData(AppStrings.Session.login, userID);
                sm.setStoreData(AppStrings.Session.password, Password);
                alertMessage(this, Message, userID, Password);


            } else {

                AppMethods.alertWithOk(this, Message);


            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /*public void alertWithOk(final Context context, final String message) {

        AlertDialog.Builder alertDialogBuilder;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            alertDialogBuilder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert);
        } else {
            alertDialogBuilder = new AlertDialog.Builder(context);
        }

        alertDialogBuilder.setMessage(message).setCancelable(false).setPositiveButton(context.getResources().getString(R.string.ok),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                showPDialog();

                                hidePDialog();
                            }
                        }, AppIntegers.loading_time);

                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }
*/
    public void alertMessage(final Context context, final String message, final String userID, final String Password) {
        AlertDialog.Builder alertDialogBuilder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            alertDialogBuilder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Light_Dialog_Alert);
        } else {
            alertDialogBuilder = new AlertDialog.Builder(this);
        }
        alertDialogBuilder.setMessage(message).setCancelable(false).setPositiveButton(getResources().getString(R.string.ok),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                     //   LinphoneAddress.TransportType transport = LinphoneAddress.TransportType.LinphoneTransportUdp;
                   /*passing data to signup fragment and then HomeSceen redirection */

                        Intent intent = new Intent();
                        intent.putExtra("user_name", userID);
                        intent.putExtra("password", Password);
                        setResult(AppIntegers.signup_frag, intent);
                        finish();


                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }


    @Override
    public void onAsyncHttpResponseGet(String response, String URL) throws JSONException {
        if (URL.equals(RestApis.verify_otp)) {
            otpVerficationResponse(response);
        } else if (URL.equals(RestApis.resend_otp)) {
            resendOtpResponse(response);
        }
    }

    public void showingLoader(String userID, String Password) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                showPDialog();


            }
        }, AppIntegers.loading_time);

    }

    private void hidePDialog() {
        if (pd != null) {
            pd.dismiss();
            pd = null;
        }
    }

    private void showPDialog() {
        pd = new ProgressDialog(OtpVerification.this);
        // Showing progress dialog before making http request
        pd.setMessage(getString(R.string.accnt_validation));
        pd.setCancelable(false);
        pd.show();
    }

}

