package com.pixelnx.localhelp.ui.user;

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 androidx.appcompat.app.AppCompatActivity;

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.ModelOrderListData;

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;


public class OrderHistoryDetails extends AppCompatActivity 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="";
    ModelOrderListData.Data dataItem;
    String status="";
    String address="";
    String payType="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_details);
        mContext= OrderHistoryDetails.this;

        initial();
    }
    void initial(){
        backIv=findViewById(R.id.backIv);
        delivery=findViewById(R.id.delivery);
        deliveryCancel=findViewById(R.id.deliverycancel);
        rePayRequest=findViewById(R.id.rePayrequest);
        rePayRequest.setOnClickListener(this);
        deliveryCancel.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
          apiDelivery();
          }
      });

        details=findViewById(R.id.details);
        detailPay=findViewById(R.id.detailPay);


        insertPoint=findViewById(R.id.dynamic);
        backIv.setOnClickListener(this);

        if(getIntent().hasExtra("data")){
        dataItem=(ModelOrderListData.Data) getIntent().getSerializableExtra("data");}


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

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

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










        if(dataItem.getDeliveryStatus().equalsIgnoreCase("1")){
       status="Recieved";

            deliveryCancel.setVisibility(View.GONE);}else{
            if(dataItem.getDeliveryStatus().equalsIgnoreCase("2")) {
                status = "Cancelled";
                deliveryCancel.setVisibility(View.GONE);
            }
            if(dataItem.getDeliveryStatus().equalsIgnoreCase("0")){
          status="Pending";
                rePayRequest.setVisibility(View.GONE);}
            if(dataItem.getDeliveryStatus().equalsIgnoreCase("3")){
                status="Cancelled By You";
                deliveryCancel.setVisibility(View.GONE);

            }
            if(dataItem.getDeliveryStatus().equalsIgnoreCase("4")){
rePayRequest.setVisibility(View.GONE);
                deliveryCancel.setVisibility(View.GONE);
                status="Refunded & Cancelled";
            }
        }
if(dataItem.getPaymentType().equalsIgnoreCase("Cash On Delivery")){
    rePayRequest.setVisibility(View.GONE);

}

        delivery.setText("Total -   ₹"+dataItem.getTotalAmount()  );
        details.setText("Store Details\n"+dataItem.getUserName()+"\nAddress : "+address+"\nMobile No. : "+dataItem.getUserMobile()
                );
        payType=""+dataItem.getPaymentType();

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

            LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            assert layoutInflater != null;
            view = layoutInflater.inflate(R.layout.dynamic_orderlist, null);
            CustomTextMedium itemName=view.findViewById(R.id.itemname);
            CustomTextMedium itemDetails=view.findViewById(R.id.itemdetails);
            CustomTextMedium itemTotal=view.findViewById(R.id.itemttl);
            itemTotal.setText("Total = ₹ "+dataItem.getItem().get(i).getAmount()+"");
            ImageView ivImage=view.findViewById(R.id.ivImage);
            Picasso
                   .get()
                    .load(Consts.Status.BASE_IMAGE_URL + dataItem.getItem().get(i).getImage())
                    .placeholder(R.drawable.noimagee)
                    .into(ivImage);
            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.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
            count++;
        }



    }


    void apiDelivery(){

        ProjectUtils.showProgressDialog(mContext, false, "Loading...");
        AndroidNetworking.post(Consts.Status.BASE_URL +"order_completed")
                .addBodyParameter("oder_id",""+id)
                .addBodyParameter("delivery_status","3")
                .setPriority(Priority.IMMEDIATE)
                .setTag(Consts.Status.SEARCH_API)
                .build()
                .getAsString(new StringRequestListener() {
                    @Override
                    public void onResponse(String response) {
                        ProjectUtils.pauseProgressDialog();

                        try {
                            JSONObject jsonObject=new JSONObject(response);

                            if(jsonObject.getString("status").equalsIgnoreCase("1")){
                            Toast.makeText(mContext,"Order Cancel !!",Toast.LENGTH_SHORT).show();
                     if(payType.equalsIgnoreCase("Cash On Delivery")){
                                Intent intent=new Intent(mContext,ActivityPreviousOrderList.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                     }else{
                         Intent intent=new Intent(mContext,ActivityRefundRequest.class);
                         intent.putExtra("data",dataItem);
                         intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                         startActivity(intent);
                     finish();}

                           }else{
                                Toast.makeText(mContext,"Try Again !",Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }

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


                    }
                });


    }

    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.backIv) {
            onBackPressed();
            finish();
        } else if (viewId == R.id.rePayrequest) {
            Intent intent = new Intent(mContext, ActivityRefundRequest.class);
            intent.putExtra("data", dataItem);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            startActivity(intent);
        }

    }
}
