package com.pixelnx.localhelp.ui.base;




import androidx.cardview.widget.CardView;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.ParsedRequestListener;
import com.androidnetworking.interfaces.StringRequestListener;
import com.pixelnx.localhelp.R;
import com.pixelnx.localhelp.model.ModelSearchItem;
import com.pixelnx.localhelp.model.ModelUserData;
import com.pixelnx.localhelp.ui.home.AdapterDialogOrder;
import com.pixelnx.localhelp.ui.home.HomeInterface;
import com.pixelnx.localhelp.utils.Consts;
import com.pixelnx.localhelp.utils.ProjectUtils;
import com.pixelnx.localhelp.utils.sharedpref.SharedPref;
import com.pixelnx.localhelp.utils.widgets.CustomButton;
import com.pixelnx.localhelp.utils.widgets.CustomEditText;

import com.pixelnx.localhelp.utils.widgets.CustomTextMedium;
import com.pixelnx.localhelp.utils.widgets.CustomTextSemiBold;
import com.pixelnx.localhelp.utils.widgets.CustomTextViewRegular;
import com.razorpay.Checkout;
import com.razorpay.PaymentResultListener;
import com.squareup.picasso.Picasso;

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

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ActivityBase extends Activity implements HomeInterface, PaymentResultListener {
    private RelativeLayout rlMain;
    protected CustomTextMedium tvOrderTotal;
    protected CustomTextSemiBold tvOrderNow;
    private ArrayList<String> navItems;
    protected DrawerLayout drawerLayout;
    ListView drawerListView;
  public   Context mContext;
    public SharedPref sharedPref;
  public  ModelUserData modelUserData;
    CustomTextViewRegular tvName;
    CustomTextViewRegular tvEmail;
    ImageView ivUserImage;
   public static  ArrayList<ModelSearchItem.Data> dataArrayList;
public static   String vendorOrStoreId="";
public static   String orderItemsFinal="";
 String paymentType="";
   String transactionId="";
 public static  double total=0;
    CustomTextMedium totalAmount;
    AdapterDialogOrder adapterDialogOrder;
    RecyclerView rvOrders;
    AdapterNavItems adapterNavItems;
   Dialog  dialogPayment;
CardView rvOrderRes;
    String count="0";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        mContext=getApplicationContext();
        rlMain = findViewById(R.id.rlMain);
        tvOrderTotal = findViewById(R.id.tvOrderTotal);
        tvOrderNow = findViewById(R.id.tvOrderNow);
        tvName = findViewById(R.id.tvName);
        rvOrderRes = findViewById(R.id.rvorderRes);
        tvEmail = findViewById(R.id.tvEmail);
        tvName.setTextSize(16f);
        tvEmail.setTextSize(13f);
        sharedPref = SharedPref.getInstance(mContext);
        modelUserData = sharedPref.getUser(Consts.Status.SP);


        if(dataArrayList==null){
        dataArrayList=new ArrayList<>();}else{

            tvOrderTotal.setText("Total item " + dataArrayList.size() + "  |  " + total + " Rs");
            if(dataArrayList.isEmpty()){
                rvOrderRes.setVisibility(View.GONE);
            }else {
                rvOrderRes.setVisibility(View.VISIBLE);
            }
        }




        Checkout.preload(getApplicationContext());
        if (ProjectUtils.checkConnection(mContext)) {
            initial();

        } else {
            Toast.makeText(mContext, "No internet connection...Try again! ", Toast.LENGTH_SHORT).show();


        }

    }
    void countApi(){

        AndroidNetworking.post(Consts.Status.BASE_URL + Consts.Status.COUNT_NOTICE_API)
                .addBodyParameter(Consts.Status.USER_ID,""+modelUserData.getData().getUserId())
                .setPriority(Priority.IMMEDIATE)
                .setTag(Consts.Status.SEARCH_API)
                .build()
                .getAsString(new StringRequestListener() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jsonObject=new JSONObject(response);
                            if(jsonObject.getString("status").equalsIgnoreCase("1")){
                                count=jsonObject.getString("userNotice");

                                mContext = ActivityBase.this;
                                navItems = new ArrayList<>();
                                navItems.add("Home");
                                navItems.add("Profile");
                                navItems.add("History Order");
                                navItems.add("All Store");
                                navItems.add("Notifications ("+count+")");
                                navItems.add("Logout!");
                                adapterNavItems = new AdapterNavItems(mContext, navItems);

                                drawerListView.setAdapter(adapterNavItems);
                            }



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

                        ProjectUtils.pauseProgressDialog();
                    }

                    @Override
                    public void onError(ANError anError) {

                        ProjectUtils.pauseProgressDialog();

                    }
                });
    }

    void initial() {
        String email=""+modelUserData.getData().getUserEmail()+"\n"+modelUserData.getData().getUserMobile();
        tvEmail.setText(email);
        String userName=""+modelUserData.getData().getUserName();
        tvName.setText(userName);
        drawerLayout = findViewById(R.id.drawerLayout);
        ivUserImage = findViewById(R.id.ivUserImage);

        drawerListView = findViewById(R.id.drawerListView);
        Picasso.get()
                .load(Consts.Status.BASE_IMAGE_URL+"users/" + modelUserData.getData().getUserImage())
                .placeholder(R.drawable.noimage)
                .into(ivUserImage);
        drawerListView.bringToFront();
       drawerLayout.requestLayout();
        mContext = ActivityBase.this;
        navItems = new ArrayList<>();
        navItems.add("Home");
        navItems.add("Profile");
        navItems.add("History Order");
        navItems.add("All Store");
        navItems.add("Notifications");
        navItems.add("Logout!");
        adapterNavItems = new AdapterNavItems(mContext, navItems);

        drawerListView.setAdapter(adapterNavItems);

        tvOrderNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dataArrayList.isEmpty()) {
                    Toast.makeText(mContext, "No Items Selected...", Toast.LENGTH_SHORT).show();
                } else {
                    congratsDialog();
                }
            }
        });

    }

    public void setContentBaseView(int layoutId) {
        rlMain.addView(LayoutInflater.from(ActivityBase.this).inflate(layoutId, null, false), 0);
    }
    void img(){

        Picasso.get()
                .load(Consts.Status.BASE_IMAGE_URL+"users/" + modelUserData.getData().getUserImage())
                .placeholder(R.drawable.noimage)
                .into(ivUserImage);
    }



    @Override
    public  void addToCart(ModelSearchItem.Data data, int type) {
        data.setTyp("" + type);
        if (data != null) {

            if (dataArrayList.size() == 0) {

                Toast.makeText(mContext,
                        "Added to cart!!", Toast.LENGTH_SHORT).show();
                dataArrayList.add(data);

              total = 0;
                for (int i = 0; i < dataArrayList.size(); i++) {
                    total = total + Double.parseDouble(dataArrayList.get(i).getRate()) * type;
                }

                tvOrderTotal.setText("Total item " + dataArrayList.size() + "  |  " + total + " Rs");
            } else {

                if (!dataArrayList.contains(data)) {
                    for (int i = 0; i < dataArrayList.size(); i++) {
                        if (dataArrayList.get(i).getSubCatId().equalsIgnoreCase("" + data.getSubCatId())) {
                            if (!dataArrayList.get(i).getTyp().equalsIgnoreCase("" + data.getTyp())){
                                Toast.makeText(mContext, "Item Qty Updated", Toast.LENGTH_SHORT).show();
                                break;}

                        } else {
                            Toast.makeText(mContext,
                                    "Added to cart!!", Toast.LENGTH_SHORT).show();
                            dataArrayList.add(data);

                           total=0;
                            for (int x = 0; x < dataArrayList.size(); x++) {

                               double res=(Double.parseDouble(dataArrayList.get(x).getRate())*Double.parseDouble(dataArrayList.get(x).getTyp()));

                                total = total + res;

                            }

                            tvOrderTotal.setText("Total item " + dataArrayList.size() + "  |  " + total + " Rs");
                            break;
                        }
                    }
                } else {


                        for (int i = 0; i < dataArrayList.size(); i++) {
                            if (dataArrayList.get(i).getSubCatId().equalsIgnoreCase("" + data.getSubCatId())) {

                                if (!dataArrayList.get(i).getTyp().equalsIgnoreCase("" + data.getTyp())){
                                    Toast.makeText(mContext, "Item Qty Updated", Toast.LENGTH_SHORT).show();
                                    break;}

                            }

                        }

                }
            }


        }

cal();
    }
    void cal(){
        total=0;
        for (int i = 0; i < dataArrayList.size(); i++) {
            double amt = Integer.parseInt(dataArrayList.get(i).getTyp()) * Double.parseDouble(dataArrayList.get(i).getRate());

            total=total+amt;
        }
        tvOrderTotal.setText("Total item " + dataArrayList.size() + "  |  " + total + " Rs");
        if(dataArrayList.isEmpty()){

            rvOrderRes.setVisibility(View.INVISIBLE);
        }else{
            rvOrderRes.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void updateList(List<ModelSearchItem.Data> data) {
         total=0;
        for (int x = 0; x < dataArrayList.size(); x++) {

            total = total + Integer.parseInt(dataArrayList.get(x).getRate()) * Integer.parseInt(dataArrayList.get(x).getTyp());
        }

        totalAmount.setText("Total Amount - " + total);
        tvOrderTotal.setText("Total item " + dataArrayList.size() + "  |  " + total + " Rs");
        adapterDialogOrder = new AdapterDialogOrder(dataArrayList, mContext);
        rvOrders.setAdapter(adapterDialogOrder);
    }

    public void congratsDialog() {

        final Dialog dialog = new Dialog(mContext, R.style.DialogTheme);
        Objects.requireNonNull(dialog.getWindow()).setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        dialog.setContentView(R.layout.layout_order);

       rvOrders = dialog.findViewById(R.id.rvOrders);
        final CustomTextMedium addressDelivery = dialog.findViewById(R.id.addressDeliv);
        CustomTextMedium addressChange = dialog.findViewById(R.id.addressChange);
        ImageView backIv = dialog.findViewById(R.id.backIv);
        backIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        addressChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Dialog dia = new Dialog(mContext, R.style.DialogTheme);
                Objects.requireNonNull(dia.getWindow()).setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

                dia.setContentView(R.layout.layout_change);
                dia.show();
                CustomTextMedium cancel=dia.findViewById(R.id.cancel);
                CustomTextMedium change=dia.findViewById(R.id.change);
              final   CustomEditText mobile=dia.findViewById(R.id.etmbl);
                mobile.setText(""+modelUserData.getData().getUserMobile());

               final CustomEditText district=dia.findViewById(R.id.district);
               final CustomEditText colony=dia.findViewById(R.id.colony);
               final CustomEditText wardNumber=dia.findViewById(R.id.wardnum);
                final CustomEditText houseNum=dia.findViewById(R.id.houseNum);
                String add=modelUserData.getData().getAddress().trim();
                if(add.contains("|")){
                    String str=add.replace("|",",");
                    String[] parts = str.split(",");


                    district.setText(parts[0]);
                    colony.setText(parts[2]);
                    wardNumber.setText(parts[1]);
                    houseNum.setText(parts[3]);
                }
                change.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(houseNum.getText().toString().isEmpty()){
                            houseNum.setError("Enter house number.");
                            houseNum.requestFocus();
                        }else{
                            if(wardNumber.getText().toString().isEmpty()){
                                wardNumber.setError("Enter ward number");
                                wardNumber.requestFocus();
                            }else{
                                if(colony.getText().toString().isEmpty()){
                                    colony.setError("Enter area / colony");
                                    colony.requestFocus();
                                }else{
                                    if(district.getText().toString().isEmpty()){
                                        district.setError("Enter district.");
                                        district.requestFocus();
                                    }else{
                                if(mobile.getText().toString().isEmpty()){
                                    mobile.setError("Mobile number required.");
                                    mobile.requestFocus();
                                }else{
                        String address= district.getText().toString()+"|"+wardNumber.getText().toString()+"|"+colony.getText().toString()+"|"+houseNum.getText().toString();
                        ProjectUtils.showProgressDialog(mContext, false, "Loading...");
                        AndroidNetworking.post(Consts.Status.BASE_URL +Consts.Status.API_USER_UPDATE)
                                .addBodyParameter(Consts.Status.USER_ID,""+modelUserData.getData().getUserId())
                                .addBodyParameter("u_mobile",""+mobile.getText().toString())
                                .addBodyParameter("address",""+address)
                                .build()
                                .getAsObject(ModelUserData.class, new ParsedRequestListener<ModelUserData>() {
                                    @Override
                                    public void onResponse(ModelUserData response) {

                                        if(response.getStatus().equalsIgnoreCase("1")){

                                            Toast.makeText(mContext,"Updated Sucessfully...",Toast.LENGTH_SHORT).show();
                                            ProjectUtils.pauseProgressDialog();
                                           sharedPref = SharedPref.getInstance(mContext);
                                            sharedPref.setBooleanValue(Consts.Status.IS_REGIS,true);
                                            SharedPref.setUser(Consts.Status.SP,response);
                                            modelUserData = sharedPref.getUser(Consts.Status.SP);
                                            String add=modelUserData.getData().getAddress().trim();
                                            String address="";
                                            if(add.contains("|")){
                                                String string=add.replace("|",",");
                                                String[] parts = string.split(",");

                                                address=""+parts[1]+","+parts[3]+" "+parts[2]+","+parts[0];

                                            }
                                            dia.dismiss();
                                            String placeHolder="Delivery At -\n"+address+"\nMobile No.-  "+modelUserData.getData().getUserMobile();
                                            addressDelivery.setText(placeHolder);
                                        }
                                    }

                                    @Override
                                    public void onError(ANError anError) {

                                        ProjectUtils.pauseProgressDialog();
                                    }
                                });}}}}}
                    }
                });
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dia.dismiss();
                    }
                });


            }
        });
        String add=modelUserData.getData().getAddress().trim();
        String address="";
        if(add.contains("|")){
            String string=add.replace("|",",");
            String[] parts = string.split(",");

            address=""+parts[1]+","+parts[3]+" "+parts[2]+","+parts[0];

        }
        String placeHolder="Delivery At -\n"+address+"\nMobile No.-  "+modelUserData.getData().getUserMobile();
        addressDelivery.setText(placeHolder);
        CustomButton customButton = dialog.findViewById(R.id.submit);
        CustomButton cancelOrder = dialog.findViewById(R.id.cancelOrder);
        cancelOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dataArrayList = new ArrayList<>();
                total=0;

                tvOrderTotal.setText("Total item " + dataArrayList.size() + "  |  " + 0 + " Rs");
                Toast.makeText(mContext, "Empty Cart ,Start Shopping...", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });

        customButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("party_name", "" + modelUserData.getData().getUserName());
                    jsonObject.put("user_id", "" + modelUserData.getData().getUserId());
                    jsonObject.put("vendor_id", "" + vendorOrStoreId);
                    jsonObject.put("invoice_total", "" + total);
                    jsonObject.put("old_invoiceid", "");
                    JSONArray itemIds = new JSONArray();
                    JSONArray itemQty = new JSONArray();
                    JSONArray itemRate = new JSONArray();
                    JSONArray itemAmount = new JSONArray();
total=0;
                    for (int i = 0; i < dataArrayList.size(); i++) {
                        itemIds.put("" + dataArrayList.get(i).getSubCatId());

                        itemQty.put("" + dataArrayList.get(i).getTyp());
                        if (!dataArrayList.get(i).getTyp().isEmpty()) {
                            double amt = Integer.parseInt(dataArrayList.get(i).getTyp()) * Double.parseDouble(dataArrayList.get(i).getRate());
                            itemAmount.put("" + amt);
                            total=total+amt;
                        } else {
                            itemAmount.put("0");
                        }

                        itemRate.put("" + dataArrayList.get(i).getRate());
                    }
                    tvOrderTotal.setText("Total item " + dataArrayList.size() + "  |  " + total + " Rs");

                    jsonObject.put("qty", itemQty);
                    jsonObject.put("rate", itemRate);
                    jsonObject.put("item_id", itemIds);
                    jsonObject.put("amount", itemAmount);



                    if(dataArrayList.size() > 0){
                    if(total > 0){
                        orderItemsFinal=""+jsonObject;
                        dialog.dismiss();
                        dialogPaymentGateway(orderItemsFinal);

                }}else{
                        dialog.dismiss();
                        Toast.makeText(mContext, "No Items Selected,Start Shopping...", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });

        rvOrders.setLayoutManager(new LinearLayoutManager(mContext));
     adapterDialogOrder = new AdapterDialogOrder(dataArrayList, mContext);
        rvOrders.setAdapter(adapterDialogOrder);
        total=0;
        for (int i = 0; i < dataArrayList.size(); i++) {
            double amt = Integer.parseInt(dataArrayList.get(i).getTyp()) * Double.parseDouble(dataArrayList.get(i).getRate());

            total=total+amt;
        }



        totalAmount = dialog.findViewById(R.id.total);
        totalAmount.setText("Grand Total Amount - ₹ " + total+"");
        tvOrderTotal.setText("Total item " + dataArrayList.size() + "  |  " + total + " Rs");


       dialog.show();

    }
void dialogPaymentGateway(final String orderdatalist){

    dialogPayment = new Dialog(mContext, R.style.DialogTheme);
    Objects.requireNonNull( dialogPayment.getWindow()).setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    dialogPayment.setContentView(R.layout.layout_paymentgateway);

ImageView sideBtn= dialogPayment.findViewById(R.id.sidebtn);
    CustomTextSemiBold totalAmountTv= dialogPayment.findViewById(R.id.ttlamttv);
    CustomButton submit= dialogPayment.findViewById(R.id.submit);
    final RadioButton rbCashOnDelivery= dialogPayment.findViewById(R.id.rbT);
    final RadioButton rbOnlinePayment= dialogPayment.findViewById(R.id.rbF);
    totalAmountTv.setText("Total Amount -  "+total+" Rs.");
sideBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
         dialogPayment.dismiss();
    }
});
submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if(rbCashOnDelivery.isChecked()){
            paymentType="Cash On Delivery";
            transactionId="";
        createOrder("" +orderdatalist);

       }else{
            if(rbOnlinePayment.isChecked()){
                paymentType="Online Payment";
startPayment(""+total);

            }else{
                Toast.makeText(mContext,"Please,Select Payment Option !",Toast.LENGTH_SHORT).show();


            }
        }
    }
});

     dialogPayment.show();
}

    private void createOrder(String sData) {

        AndroidNetworking.post(Consts.Status.BASE_URL + Consts.Status.CREATE_SALEINVOICE_API)
                .addBodyParameter("item_Arr", sData)
                .addBodyParameter("payment_type", ""+paymentType)
                .addBodyParameter("transaction_id", ""+transactionId)
                .setPriority(Priority.IMMEDIATE)
                .setTag(Consts.Status.SEARCH_API)
                .build()
                .getAsString(new StringRequestListener() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            dialogPayment.dismiss();

                           if(jsonObject.getString("status").equalsIgnoreCase("1")){
                            dataArrayList = new ArrayList<>();
                            total=0;
                                 Toast.makeText(mContext, "" + jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();

                            tvOrderTotal.setText("Total item " + dataArrayList.size() + "  |  " + 0 + " Rs");}
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(ANError anError) {
                        Toast.makeText(mContext, anError.getErrorDetail(), Toast.LENGTH_SHORT).show();
                    }
                });

    }
    @Override
    protected void onResume() {
        super.onResume();
        if (this.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            this.drawerLayout.closeDrawer(GravityCompat.START);
        }
        img();

        countApi();
    }

    @Override
    public void onPaymentSuccess(String s) {
        Toast.makeText(getApplicationContext(),"Payment Done !",Toast.LENGTH_SHORT).show();
        transactionId=s;
        createOrder(""+orderItemsFinal);

    }

    @Override
    public void onPaymentError(int i, String s) {
        Toast.makeText(getApplicationContext(),"Cancel",Toast.LENGTH_SHORT).show();
    }
    public void startPayment(String payments) {

        final Checkout checkout = new Checkout();
        final Activity activity = this;
        try {
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("name","Home Delivery");
            jsonObject.put("description","PixelNx");
            jsonObject.put("currency","INR");
            jsonObject.put("image", "https://s3.amazonaws.com/rzp-mobile/images/rzp.png");
          jsonObject.put("payment_capture", true);

            String payment=""+payments;
            double totalPay= Double.parseDouble(payment);
            totalPay=totalPay*100;

            jsonObject.put("amount",""+totalPay);
            checkout.open(activity,jsonObject);

        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(),"Error in payment",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }



    }
}
