package com.pixelnx.localhelp.ui.order;


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.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
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.widgets.CustomButton;
import com.pixelnx.localhelp.utils.widgets.CustomTextExtraBold;
import com.pixelnx.localhelp.utils.widgets.CustomTextMedium;

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 ActivityOrderCart extends Activity implements View.OnClickListener, HomeInterface {
ImageView sideDrawer;
Context mContext;
    ArrayList<ModelSearchItem.Data> dataArrayList;
    ModelUserData modelUserData;
    CustomTextExtraBold totalAmount;
    String vendorOrStoreId="";
    double total = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_cart);
        mContext=ActivityOrderCart.this;
        initial();
    }
    void initial(){
        sideDrawer=findViewById(R.id.sideDrawer);
        sideDrawer.setOnClickListener(this);
        dataArrayList = new ArrayList<>();

        if (dataArrayList.size() == 0) {
            Toast.makeText(mContext, "No Items Selected...", Toast.LENGTH_SHORT).show();
        } else {
            congratsDialog();
        }
    }

    private 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);

        RecyclerView rvOrders = dialog.findViewById(R.id.rvOrders);
        CustomTextMedium addressDelivery = dialog.findViewById(R.id.addressDeliv);
        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];

        }
        addressDelivery.setText("Home Delivery At - "+address+"\nMobile Number-  "+modelUserData.getData().getUserMobile());
        CustomButton customButton = dialog.findViewById(R.id.submit);
        totalAmount = dialog.findViewById(R.id.total);
        totalAmount.setText("Grand Total Amount - " + total+" Rs.");
        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 itemAmts = new JSONArray();

                    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()) {
                            int amt = Integer.parseInt(dataArrayList.get(i).getTyp()) * Integer.parseInt(dataArrayList.get(i).getRate());
                            itemAmts.put("" + amt);
                        } else {
                            itemAmts.put("0");
                        }

                        itemRate.put("" + dataArrayList.get(i).getRate());
                    }


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


                    dialog.dismiss();
                    createOrder("" + jsonObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });

        rvOrders.setLayoutManager(new LinearLayoutManager(mContext));
        AdapterDialogOrder adapterDialogOrder = new AdapterDialogOrder(dataArrayList, mContext);
        rvOrders.setAdapter(adapterDialogOrder);


        dialog.show();

    }

    private void createOrder(String sData) {

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

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Toast.makeText(mContext, "" + jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                            dataArrayList =new ArrayList<>();

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

                    }

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

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.sideDrawer) {
            onBackPressed();
        }
    }


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

            if (dataArrayList.size() == 0) {
                dataArrayList.add(data);

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

            } else {
                if (!dataArrayList.contains(data)) {
                    for (int i = 0; i < dataArrayList.size(); i++) {
                        if (dataArrayList.get(i).getSubCatName().contains("" + data.getSubCatName())) {
                            Toast.makeText(mContext, data.getSubCatName() + " Already Exist", Toast.LENGTH_SHORT).show();
                        } else {
                            dataArrayList.add(data);


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

                            break;
                        }
                    }
                } else {
                    Toast.makeText(mContext, "Item Already Exist", Toast.LENGTH_SHORT).show();

                }
            }


        }


    }

    @Override
    public void updateList(List<ModelSearchItem.Data> data) {
        throw new UnsupportedOperationException();

    }
}
