package com.pixelnx.localhelp.ui.order;



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


import android.view.LayoutInflater;
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.utils.Consts;
import com.pixelnx.localhelp.utils.ProjectUtils;
import com.pixelnx.localhelp.utils.widgets.CustomTextMedium;
import com.pixelnx.localhelp.utils.widgets.CustomTextSemiBold;
import com.squareup.picasso.Picasso;

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

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

public class OrderDetails extends Activity implements View.OnClickListener {
Context mContext;
ImageView backIv;
    ArrayList<View> viewArray;
   ViewGroup insertPoint;
    View view;
    int count=0;
    CustomTextSemiBold delivery;
    CustomTextSemiBold deliveryCancel;
    CustomTextMedium details;
    CustomTextMedium detailPay;
    CustomTextMedium rePayRequest;
    String id="";
    ModelNewOrderData.Data dataItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_details);
        mContext= OrderDetails.this;
        initial();
    }
    void initial(){
        backIv=findViewById(R.id.backIv);
        delivery=findViewById(R.id.delivery);
        deliveryCancel=findViewById(R.id.deliverycancel);
        details=findViewById(R.id.details);
        detailPay=findViewById(R.id.detailPay);
        rePayRequest=findViewById(R.id.rePayrequest);
        rePayRequest.setVisibility(View.GONE);

        if(getIntent().hasExtra("tag")){

            if(Objects.requireNonNull(getIntent().getStringExtra("tag")).equalsIgnoreCase("D")){
              delivery.setVisibility(View.GONE);
             deliveryCancel.setVisibility(View.GONE);
            }
            if(Objects.requireNonNull(getIntent().getStringExtra("tag")).equalsIgnoreCase("C")){
                delivery.setVisibility(View.GONE);
                deliveryCancel.setVisibility(View.GONE);
            }

        }
        insertPoint=findViewById(R.id.dynamic);
        backIv.setOnClickListener(this);
        delivery.setOnClickListener(this);
        deliveryCancel.setOnClickListener(this);
        if(getIntent().hasExtra("data")){
        dataItem=(ModelNewOrderData.Data)getIntent().getSerializableExtra("data");}


        assert dataItem != null;
        id=dataItem.getId();

        if(!dataItem.getUserCity().isEmpty()){
        String string=dataItem.getUserCity().replace("|",",");
        String[] parts = string.split(",");

        String address=""+parts[1]+","+parts[3]+" "+parts[2]+" ,"+parts[0];
        details.setText("Customer Deatils\n"+dataItem.getPartyName()+"\nMobile No. : "+dataItem.getUserMobile()+"" +
                "\nAddress : "+address+"");}else{
            details.setText("Customer Deatils\n"+dataItem.getPartyName()+"\nMobile No. : "+dataItem.getUserMobile()+"" +
                    "\nAddress : "+dataItem.getUserCity()+"");

        }
        detailPay.setText("Order Details\nAmount  : ₹ "+dataItem.getTotalAmount()+"\nTotal Qty : "+dataItem.getOrdersTotal()+"\nPayment : "+dataItem.getPaymentType());
        viewArray=new ArrayList<>();
        for(int i=0;i<dataItem.getItem().size();i++){

            LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            assert vi != null;
            view = vi.inflate(R.layout.dynamic_orderlist, null);
            CustomTextMedium itemName=view.findViewById(R.id.itemname);
            ImageView ivImage=view.findViewById(R.id.ivImage);
            CustomTextMedium itemTotal=view.findViewById(R.id.itemttl);
            itemTotal.setText("Total = ₹ "+dataItem.getItem().get(i).getAmount()+"");
            Picasso
               .get()
                    .load(Consts.Status.BASE_IMAGE_URL + dataItem.getItem().get(i).getImage())
                    .placeholder(R.drawable.noimagee)
                    .into(ivImage);

            CustomTextMedium itemDetails=view.findViewById(R.id.itemdetails);
            itemName.setText(""+dataItem.getItem().get(i).getItemName()+"  ("+dataItem.getItem().get(i).getItemStockWeight()+dataItem.getItem().get(i).getQntUnit()+")");
            itemDetails.setText("QTY : "+dataItem.getItem().get(i).getQuantity()+"\n" +
                    "RATE : ₹ "+dataItem.getItem().get(i).getRate()+"    "+"");
            viewArray.add(view);
            insertPoint.addView(view, count, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            count++;
        }


    }

    void apiDelivery(final String tag){
        ProjectUtils.showProgressDialog(mContext, false, "Loading...");
        AndroidNetworking.post(Consts.Status.BASE_URL + Consts.Status.ORDER_COMPLETED_API)
                .addBodyParameter("oder_id",""+id)
                .addBodyParameter("delivery_status",""+tag)
                .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")){
                                if(!tag.equalsIgnoreCase("2")){
                            Toast.makeText(mContext,"Order Deliver!!",Toast.LENGTH_SHORT).show();}else{
                                    Toast.makeText(mContext,"Order Cancelled!!",Toast.LENGTH_SHORT).show();
                                }

                            Intent i=new Intent(mContext,ActivityNewOrder.class);

                            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(i);}else{
                                Toast.makeText(mContext,"Try Again !",Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        ProjectUtils.pauseProgressDialog();

                    }

                    @Override
                    public void onError(ANError anError) {
                        ProjectUtils.pauseProgressDialog();


                    }
                });


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.backIv:
                onBackPressed();
                break;

            case R.id.delivery:

                apiDelivery("1");
                break;
            case R.id.deliverycancel:

                apiDelivery("2");
                break;

        }

    }
}
