package ch.pizzalemon.android.fragment;

import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import ch.pizzalemon.android.R;
import ch.pizzalemon.android.activity.BaseActivity;
import ch.pizzalemon.android.activity.MainActivity;
import ch.pizzalemon.android.activity.OrderHistoryDetailsActivity;
import ch.pizzalemon.android.adapter.recycler.OrderHistoryRecyclerAdapter;
import ch.pizzalemon.android.api.ApiEndPoints;
import ch.pizzalemon.android.api.ApiErrorUtils;
import ch.pizzalemon.android.api.ApiService;
import ch.pizzalemon.android.api.ResponseArray;
import ch.pizzalemon.android.api.ResponseObject;
import ch.pizzalemon.android.helper.DialogHelper;
import ch.pizzalemon.android.helper.SessionHelper;
import ch.pizzalemon.android.interfaces.RecyclerItemClickListener;
import ch.pizzalemon.android.model.history.OrderHistoryModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by cimenmus on 20/09/2017.
 */

public class OrderHistoryFragment extends BaseFragment {

    @BindView(R.id.orderHistoryRecyclerView) RecyclerView orderHistoryRecyclerView;

    @BindString(R.string.bottom_nav_menu_item_history) String fragmentTitle;

    public static final java.lang.String FRAGMENT_NAME = "historyFragment";

    private ArrayList<OrderHistoryModel> orderHistoryList = new ArrayList<>();
    private OrderHistoryRecyclerAdapter orderHistoryRecyclerAdapter;

    public OrderHistoryFragment() {}

    public static OrderHistoryFragment newInstance() {
        return new OrderHistoryFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order_history, container, false);
        ButterKnife.bind(this, view);
        initViews();
        getOrderHistory();
        return view;
    }

    private void initViews(){
        setPizzalinkToolbarFields(false, fragmentTitle);
        initRecyclerView();
    }

    private void initRecyclerView(){
        orderHistoryRecyclerAdapter = new OrderHistoryRecyclerAdapter(orderHistoryList, new RecyclerItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                switch (view.getId()){
                    case R.id.repeatOrderTextView:
                        clearCart(orderHistoryList.get(position).getId());
                        break;
                    default:
                        Intent orderHistoryDetailsIntent = new Intent(BaseActivity.currentActivity, OrderHistoryDetailsActivity.class);
                        orderHistoryDetailsIntent.putExtra("orderHistoryModel", orderHistoryList.get(position));
                        startActivity(orderHistoryDetailsIntent);
                }
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(BaseActivity.currentActivity);
        orderHistoryRecyclerView.setLayoutManager(layoutManager);
        orderHistoryRecyclerView.setAdapter(orderHistoryRecyclerAdapter);
    }

    // "cP1sbSmwc6GEE7fCy6du7KqRbkR7bY1q"
    /*
    private void getOrderHistory(){
        DialogHelper.showLoadingDialog();
        HashMap<String, Object> params = new HashMap<>();
        params.put("token", SessionHelper.getCustomerToken().getToken());
        Call<OrderHistoryResponseModel> call = ApiService.apiInterface.getOrderHistory(SessionHelper.getCustomerToken().getToken());
        call.enqueue(new Callback<OrderHistoryResponseModel>() {
            @Override
            public void onResponse(Call<OrderHistoryResponseModel> call, Response<OrderHistoryResponseModel> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body() != null &&
                        response.body().isSuccess()){
                    fillAndNotifyOrderHistoryList(response.body().getData());
                }
                else
                    ApiErrorUtils.parseError(response);
            }

            @Override
            public void onFailure(Call<OrderHistoryResponseModel> call, Throwable t) {
                DialogHelper.hideLoadingDialog();
                DialogHelper.showFailedDialog();
            }
        });
    }
    */

    private void getOrderHistory(){
        DialogHelper.showLoadingDialog();
        Call<ResponseArray<OrderHistoryModel>> call = ApiService.apiInterface.
                getOrderHistory(
                        SessionHelper.getSelectedStore().getStoreName(),
                        SessionHelper.getCustomerToken().getToken());
        call.enqueue(new Callback<ResponseArray<OrderHistoryModel>>() {
            @Override
            public void onResponse(Call<ResponseArray<OrderHistoryModel>> call, Response<ResponseArray<OrderHistoryModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess())
                    fillAndNotifyOrderHistoryList(response.body().getData());
                else
                    ApiErrorUtils.parseError(response);
            }

            @Override
            public void onFailure(Call<ResponseArray<OrderHistoryModel>> call, Throwable t) {
                DialogHelper.hideLoadingDialog();
                DialogHelper.showFailedDialog();
            }
        });
    }

    private void fillAndNotifyOrderHistoryList(ArrayList<OrderHistoryModel> orderList){
        OrderHistoryModel.checkNull(orderList);
        orderHistoryList.clear();
        orderHistoryList.addAll(orderList);
        orderHistoryRecyclerAdapter.notifyDataSetChanged();
    }

    private void clearCart(final String orderId){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject> call = ApiService.apiInterface.clearCart(
                SessionHelper.getSelectedStore().getStoreName(),
                SessionHelper.getCustomerToken().getToken());
        call.enqueue(new Callback<ResponseObject>() {
            @Override
            public void onResponse(Call<ResponseObject> call, Response<ResponseObject> response) {
                if(response.isSuccessful() && response.body().isSuccess()){
                    /*
                    cartProductList.clear();
                    cartRecyclerAdapter.notifyDataSetChanged();
                    setCartLayoutsVisibility();
                    SharedPrefsHelper.setCartItemCount(0);
                    SharedPrefsHelper.setCartTotalPrice("0");
                    SharedPrefsHelper.setUserUsedPizzapassCampaign(false);
                    MainActivity mainActivity = (MainActivity) BaseActivity.currentActivity;
                    mainActivity.setCartItemCount();
                    */
                    repeatOrder(orderId);
                }

                else {
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseError(response);
                }
            }

            @Override
            public void onFailure(Call<ResponseObject> call, Throwable t) {
                DialogHelper.hideLoadingDialog();
                DialogHelper.showFailedDialog();
            }
        });
    }

    private void repeatOrder(String orderId){

        HashMap<String, Object> params = new HashMap<>();
        params.put("order_id", orderId);

        Call<ResponseObject> call = ApiService.apiInterface.repeatOrder(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_REPEAT_ORDER + SessionHelper.getCustomerToken().getToken(),
                params);
        call.enqueue(new Callback<ResponseObject>() {
            @Override
            public void onResponse(Call<ResponseObject> call, final Response<ResponseObject> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    MainActivity mainActivity = (MainActivity) BaseActivity.currentActivity;
                    mainActivity.openFragmentAt(2);
                }
                else {
                    ApiErrorUtils.parseError(response);
                }
            }

            @Override
            public void onFailure(Call<ResponseObject> call, Throwable t) {
                DialogHelper.hideLoadingDialog();
                DialogHelper.showFailedDialog();
            }
        });
    }

}
