package ch.pizzalemon.android.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.pizzalemon.android.R;
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.PriceHelper;
import ch.pizzalemon.android.helper.SessionHelper;
import ch.pizzalemon.android.helper.TextHelper;
import ch.pizzalemon.android.model.history.OrderHistoryModel;
import ch.pizzalemon.android.model.history.OrderHistoryProductModel;
import ch.pizzalemon.android.model.history.OrderHistoryProductOptionModel;
import ch.pizzalemon.android.view.AppInfoView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class OrderHistoryDetailsActivity extends BaseActivity {

    @BindView(R.id.orderDatePizzalinkInfoLayout) AppInfoView orderDatePizzalinkInfoLayout;
    //@BindView(R.id.orderStatusPizzalinkInfoLayout) PizzalinkInfoView orderStatusPizzalinkInfoLayout;
    @BindView(R.id.orderShippingTimePizzalinkInfoLayout) AppInfoView orderShippingTimePizzalinkInfoLayout;
    @BindView(R.id.orderTotalPizzalinkInfoLayout) AppInfoView orderTotalPizzalinkInfoLayout;
    @BindView(R.id.orderPaymentMethodPizzalinkInfoLayout) AppInfoView orderPaymentMethodPizzalinkInfoLayout;
    @BindView(R.id.orderProductsTextView) TextView orderProductsTextView;
    @BindView(R.id.orderFullnamePizzalinkInfoLayout) AppInfoView orderFullnamePizzalinkInfoLayout;
    @BindView(R.id.orderShippingMethodPizzalinkInfoLayout) AppInfoView orderShippingMethodPizzalinkInfoLayout;
    @BindView(R.id.orderShippingAddressPizzalinkInfoLayout) AppInfoView orderShippingAddressPizzalinkInfoLayout;
    @BindView(R.id.orderNotePizzalinkInfoLayout) AppInfoView orderNotePizzalinkInfoLayout;

    private OrderHistoryModel orderHistoryModel;
    private ArrayList<OrderHistoryProductModel> productList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_history_details);
        ButterKnife.bind(this);
        getDataFromIntent();
        getOrderProductList();
        initViews();
    }

    @OnClick(R.id.repeatOrderButton)
    public void onClick(){
        clearCart();
    }

    private void getDataFromIntent(){
        orderHistoryModel = (OrderHistoryModel) getIntent().getSerializableExtra("orderHistoryModel");
    }

    private void initViews(){
        orderDatePizzalinkInfoLayout.setText(orderHistoryModel.getFormattedCreateDate());
        //orderStatusPizzalinkInfoLayout.setText(orderHistoryModel.getStatus());
        if(orderHistoryModel.getShippingTime().isEmpty()){
            orderShippingTimePizzalinkInfoLayout.setVisibility(View.GONE);
        }
        else {
            orderShippingTimePizzalinkInfoLayout.setText(orderHistoryModel.getShippingTime());
        }
        orderTotalPizzalinkInfoLayout.setText(PriceHelper.roundFractions(orderHistoryModel.getTotalString()));
        orderPaymentMethodPizzalinkInfoLayout.setText(orderHistoryModel.getPaymentMethod());
        orderFullnamePizzalinkInfoLayout.setText(orderHistoryModel.getFirstname() + " " + orderHistoryModel.getLastname());
        orderShippingMethodPizzalinkInfoLayout.setText(orderHistoryModel.getShippingMethod());
        orderShippingAddressPizzalinkInfoLayout.setText(createAddress());
        if(orderHistoryModel.getComment().isEmpty()){
            orderNotePizzalinkInfoLayout.setVisibility(View.GONE);
        }
        else {
            orderNotePizzalinkInfoLayout.setText(orderHistoryModel.getComment());
        }
    }

    private String createAddress(){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder
                .append(orderHistoryModel.getFirstname())
                .append(" ")
                .append(orderHistoryModel.getLastname())
                .append("\n");

        if(!orderHistoryModel.getPaymentAddress1().isEmpty()){
            stringBuilder
                    .append(orderHistoryModel.getShippingAddress1())
                    .append("\n");
        }

        if(!orderHistoryModel.getShippingAddress2().isEmpty()){
            stringBuilder
                    .append(orderHistoryModel.getShippingAddress2())
                    .append("\n");
        }
         stringBuilder
                 .append(orderHistoryModel.getShippingPostcode())
                .append(" ")
                .append(orderHistoryModel.getShippingCity())
                .append("\n")
                .append(orderHistoryModel.getShippingCountry());

        return stringBuilder.toString();
    }

    private void getOrderProductList(){
        DialogHelper.showLoadingDialog();
        Call<ResponseArray<OrderHistoryProductModel>> call = ApiService.apiInterface.getOrderProductList(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_ORDER_PRODUCT_LIST + SessionHelper.getCustomerToken().getToken(), orderHistoryModel.getId());
        call.enqueue(new Callback<ResponseArray<OrderHistoryProductModel>>() {
            @Override
            public void onResponse(Call<ResponseArray<OrderHistoryProductModel>> call, Response<ResponseArray<OrderHistoryProductModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess())
                    fillAndNotifyProductList(response.body().getData());
                else
                    ApiErrorUtils.parseError(response);
            }

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

    private void fillAndNotifyProductList(ArrayList<OrderHistoryProductModel> prdctLst){
        OrderHistoryProductModel.checkNull(prdctLst);
        productList.clear();
        productList.addAll(prdctLst);
        TextHelper.setTextFromHTML(orderProductsTextView, getProductListInfoText());
    }

    private String getProductListInfoText(){
        StringBuilder stringBuilder = new StringBuilder();
        for(OrderHistoryProductModel orderHistoryProductModel : productList){
            stringBuilder
                    .append("<b>")
                    .append(orderHistoryProductModel.getQuantity())
                    .append(" x ")
                    .append(orderHistoryProductModel.getName())
                    .append(" = ")
                    .append(PriceHelper.getPriceWithCurreny(orderHistoryProductModel.getTotal()))
                    .append("</b>")
                    .append("<br/>")
                    .append(getProductInfo(orderHistoryProductModel))
                    .append("<br/>");
        }
        if(stringBuilder.toString().trim().endsWith("<br/><br/>")){
            int lastIndex = stringBuilder.toString().lastIndexOf("<br/><br/>");
            return stringBuilder.toString().trim().substring(0, lastIndex);
        }
        return stringBuilder.toString().trim();
    }

    private String getProductInfo(OrderHistoryProductModel orderHistoryProductModel){
        StringBuilder stringBuilder = new StringBuilder();
        for(OrderHistoryProductOptionModel orderHistoryProductOptionModel : orderHistoryProductModel.getOptionList()){
            if(!stringBuilder.toString().contains(orderHistoryProductOptionModel.getName())){
                /*
                if(!stringBuilder.toString().isEmpty()){
                    stringBuilder.append("<br/>");
                }
                */
                stringBuilder
                        .append("<br/>")
                        .append("<u>")
                        .append(orderHistoryProductOptionModel.getName())
                        .append("</u>")
                        .append("<br/>");
            }
            stringBuilder
                    .append("<i>")
                    .append(orderHistoryProductOptionModel.getValue())
                    .append("</i>")
                    .append("<br/>");
        }
        return stringBuilder.toString().trim();
    }

    private void clearCart(){
        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();
                }

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

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

    private void repeatOrder(){

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

        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()){
                    Intent basketIntent = new Intent(OrderHistoryDetailsActivity.this, MainActivity.class);
                    basketIntent.putExtra("isStartWithCart", true);
                    startActivity(basketIntent);
                    finishAffinity();
                }
                else {
                    ApiErrorUtils.parseError(response);
                }
            }

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

    /*
    private String getCartInfoText(CartProductModel cartProductModel){

        StringBuilder stringBuilder = new StringBuilder();

        for(int i = 0; i < cartProductModel.getOption().size(); i++){

            if(!stringBuilder.toString().contains(cartProductModel.getOption().get(i).getName())){

                if(!stringBuilder.toString().isEmpty()){
                    stringBuilder.append("<br/>");
                }
                stringBuilder
                        .append("<b>")
                        .append("<u>")
                        .append(cartProductModel.getOption().get(i).getName())
                        .append("</u>")
                        .append("</b>")
                        .append("<br/>")
                        .append("<br/>");
            }
            stringBuilder
                    .append(cartProductModel.getOption().get(i).getValue())
                    .append("<br/>");
        }

        return stringBuilder.toString().trim();
    }
    */
}
