package ch.pizzapp.android.fragment.createOrder;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.braintreepayments.api.dropin.DropInActivity;
import com.braintreepayments.api.dropin.DropInRequest;
import com.braintreepayments.api.dropin.DropInResult;
import com.google.android.gms.wallet.Cart;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import com.wdullaer.materialdatetimepicker.time.Timepoint;

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

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.pizzapp.android.R;
import ch.pizzapp.android.activity.BaseActivity;
import ch.pizzapp.android.activity.CreateOrderActivity;
import ch.pizzapp.android.adapter.recycler.OrderPriceRecyclerAdapter;
import ch.pizzapp.android.adapter.recycler.ProductOnOrderSummaryRecyclerAdapter;
import ch.pizzapp.android.api.ApiConstants;
import ch.pizzapp.android.api.ApiEndPoints;
import ch.pizzapp.android.api.ApiErrorUtils;
import ch.pizzapp.android.api.ApiService;
import ch.pizzapp.android.api.ResponseObject;
import ch.pizzapp.android.helper.DialogHelper;
import ch.pizzapp.android.helper.PriceHelper;
import ch.pizzapp.android.helper.SessionHelper;
import ch.pizzapp.android.helper.SharedPrefsHelper;
import ch.pizzapp.android.model.PaymentMethodModel;
import ch.pizzapp.android.model.StoreShiftModel;
import ch.pizzapp.android.model.StoreWorkDayModel;
import ch.pizzapp.android.model.cart.CartInfoModel;
import ch.pizzapp.android.model.cart.CartProductModel;
import ch.pizzapp.android.model.cart.CartTotalModel;
import ch.pizzapp.android.view.AppInfoView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by cimenmus on 17/10/2017.
 */

public class CreateOrderSummaryFragment extends CreateOrderBaseFragment {

    @BindView(R.id.orderPersonFullnamePizzalinkInfoLayout) AppInfoView orderPersonFullnamePizzalinkInfoLayout;
    @BindView(R.id.orderShippingMethodPizzalinkInfoLayout) AppInfoView orderShippingMethodPizzalinkInfoLayout;
    @BindView(R.id.orderShippingAddressPizzalinkInfoLayout) AppInfoView orderShippingAddressPizzalinkInfoLayout;
    @BindView(R.id.orderPaymentMethodPizzalinkInfoLayout) AppInfoView orderPaymentMethodPizzalinkInfoLayout;
    //@BindView(R.id.orderTotalPizzalinkInfoLayout) AppInfoView orderTotalPizzalinkInfoLayout;
    @BindView(R.id.orderPriceRecyclerView) RecyclerView orderPriceRecyclerView;
    @BindView(R.id.orderProductsRecyclerView) RecyclerView orderProductsRecyclerView;
    @BindView(R.id.orderNotePizzalinkInfoLayout) AppInfoView orderNotePizzalinkInfoLayout;

    @BindString(R.string.confirm_order) String confirmOrderText;
    @BindString(R.string.slice_pizza_for_store) String slicePizzaForStoreText;
    @BindString(R.string.slice_pizza) String yesText;
    @BindString(R.string.do_not_slice_pizza) String noText;
    @BindString(R.string.restaurant_out_of_order) String restaurantOutOfOrderText;
    @BindString(R.string.restaurant_out_of_order_on_selected_date) String restaurantOutOfOrderOnSelectedDateText;
    @BindString(R.string.something_went_wrong) String genericErrorText;
    @BindString(R.string.unknown_payment_method) String unknownPaymentMethodText;
    @BindString(R.string.payment_canceled) String paymentCanceledText;
    @BindString(R.string.andorid_pay_not_found) String androidPayNotFoundText;
    @BindString(R.string.choose) String choosetext;
    @BindString(R.string.alert) String alertText;
    @BindString(R.string.delivery_date) String deliveryDateText;
    @BindString(R.string.delivery_time) String deliveryTimeText;

    public static final java.lang.String FRAGMENT_NAME = "orderSummaryFragment";
    private final int REQUEST_CODE_BRAINTREE_PAYMENT = 3784;
    private CreateOrderActivity createOrderActivity;
    private String dateOfOrderString, timeOfOrder;
    private Calendar dateOfOrder;
    private ArrayList<CartTotalModel> cartTotalList = new ArrayList<>();
    private OrderPriceRecyclerAdapter orderPriceRecyclerAdapter;
    private ProductOnOrderSummaryRecyclerAdapter productOnOrderSummaryRecyclerAdapter;
    private StoreShiftModel storeShiftModel;

    public CreateOrderSummaryFragment() {}

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

    @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_create_order_summary, container, false);
        ButterKnife.bind(this, view);
        initViews();
        getCartProductsWithCommission();
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_BRAINTREE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                DropInResult result = data.getParcelableExtra(DropInResult.EXTRA_DROP_IN_RESULT);
                createOrderActivity.setSelectedPaymentMethod(result.getPaymentMethodType());
                createBraintreePayment(result);
                // use the result to update your UI and send the payment method nonce to your server
            } else if (resultCode == Activity.RESULT_CANCELED) {
                // the user canceled
                Log.i("fjehfhreuf", "vjfjvjfv");
                DialogHelper.showAlertDialog(BaseActivity.currentActivity, paymentCanceledText);
            } else {
                // handle errors here, an exception may be available in
                Exception error = (Exception) data.getSerializableExtra(DropInActivity.EXTRA_ERROR);
                DialogHelper.showAlertDialog(BaseActivity.currentActivity, error.getMessage());
            }
        }
    }

    @OnClick({R.id.previousTextView, R.id.nextTextView})
    protected void onClick(View view){
        CreateOrderActivity createOrderActivity = (CreateOrderActivity) getActivity();
        switch (view.getId()){
            case R.id.previousTextView:
                createOrderActivity.onPreviousClicked(FRAGMENT_NAME);
                break;
            case R.id.nextTextView:
                checkDeliveryTime();
                break;
        }
    }

    private void initViews(){

        nextTextView.setText(confirmOrderText);

        createOrderActivity = (CreateOrderActivity) getActivity();

        orderPersonFullnamePizzalinkInfoLayout.setText(SessionHelper.getUser().getFullname());
        orderShippingMethodPizzalinkInfoLayout.setText(createOrderActivity.getSelectedShippingMethod().getTitle());
        orderShippingAddressPizzalinkInfoLayout.setText(createOrderActivity.getSelectedShippingAddress().getAddress());
        orderPaymentMethodPizzalinkInfoLayout.setText(createOrderActivity.getSelectedPaymentMethod().getTitle());
        //orderTotalPizzalinkInfoLayout.setText(PriceHelper.roundFractions(createOrderActivity.getCartInfo().getCartTotalModel().getText()));
        if(createOrderActivity.getOrderNote().trim().isEmpty()){
            orderNotePizzalinkInfoLayout.setVisibility(View.GONE);
        }
        else {
            orderNotePizzalinkInfoLayout.setVisibility(View.VISIBLE);
            orderNotePizzalinkInfoLayout.setText(createOrderActivity.getOrderNote());
        }

        initOrderPriceRecyclerView();
        initOrderProductsRecyclerView();

    }

    private void initOrderPriceRecyclerView(){
        orderPriceRecyclerAdapter = new OrderPriceRecyclerAdapter(cartTotalList);
        orderPriceRecyclerView.setLayoutManager(new LinearLayoutManager(BaseActivity.currentActivity));
        orderPriceRecyclerView.setNestedScrollingEnabled(false);
        orderPriceRecyclerView.setAdapter(orderPriceRecyclerAdapter);
    }

    private void initOrderProductsRecyclerView(){
        productOnOrderSummaryRecyclerAdapter = new ProductOnOrderSummaryRecyclerAdapter(createOrderActivity.getCartInfo().getProducts());
        orderProductsRecyclerView.setLayoutManager(new LinearLayoutManager(BaseActivity.currentActivity));
        orderProductsRecyclerView.setNestedScrollingEnabled(false);
        orderProductsRecyclerView.setAdapter(productOnOrderSummaryRecyclerAdapter);
    }

    private void checkDeliveryTime(){
        ApiService
                .apiInterface
                .checkDeliveryTime(SessionHelper.getSelectedStore().getStoreName())
                .enqueue(new Callback<ResponseObject<Boolean>>() {
                    @Override
                    public void onResponse(Call<ResponseObject<Boolean>> call, Response<ResponseObject<Boolean>> response) {
                        if(response.isSuccessful() &&
                                response.body() != null){

                            if(response.body().isSuccess()){
                                redirectToPayment();
                            }
                            else {
                                getDeliveryTimeOfStore();
                                /*
                                DialogHelper.hideLoadingDialog();
                                showRestaurantOutOfOrderDialog(restaurantOutOfOrderText);
                                */
                            }

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

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

    private void getDeliveryTimeOfStore(){
        ApiService
                .apiInterface
                .getDeliveryTimeOfStore(SessionHelper.getSelectedStore().getStoreName())
                .enqueue(new Callback<ResponseObject<StoreShiftModel>>() {
                    @Override
                    public void onResponse(Call<ResponseObject<StoreShiftModel>> call, Response<ResponseObject<StoreShiftModel>> response) {
                        DialogHelper.hideLoadingDialog();
                        if(response.isSuccessful() &&
                                response.body() != null){

                            if(response.body().isSuccess()){
                                storeShiftModel = response.body().getData();
                                showRestaurantOutOfOrderDialog(restaurantOutOfOrderText);
                            }
                            else {
                                DialogHelper.showAlertDialog(BaseActivity.currentActivity, genericErrorText);
                            }

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

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

    private void checkDeliveryTimeWithDateAndTime(){
        DialogHelper.showLoadingDialog();
        String deliveryDateAndTime = dateOfOrderString + " " + timeOfOrder;
        ApiService
                .apiInterface
                .checkDeliveryTimeWithDateAndTime(
                        SessionHelper.getSelectedStore().getStoreName(),
                        deliveryDateAndTime)
                .enqueue(new Callback<ResponseObject<Boolean>>() {
                    @Override
                    public void onResponse(Call<ResponseObject<Boolean>> call, Response<ResponseObject<Boolean>> response) {
                        DialogHelper.hideLoadingDialog();
                        if(response.isSuccessful() &&
                                response.body() != null){

                            if(response.body().isSuccess()){
                                redirectToPayment();
                            }
                            else {
                                showRestaurantOutOfOrderDialog(restaurantOutOfOrderOnSelectedDateText);
                            }

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

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


                        /*
                        // dummy //

                        if(createOrderActivity.getSelectedPaymentMethod().getPaymentMethodType() == PaymentMethodModel.PaymentMethodType.UNKNOWN){
                            DialogHelper.hideLoadingDialog();
                            DialogHelper.showAlertDialog(BaseActivity.currentActivity, unknownPaymentMethodText);
                        }
                        else if(createOrderActivity.getSelectedPaymentMethod().getPaymentMethodType() == PaymentMethodModel.PaymentMethodType.CASH ||
                                createOrderActivity.getSelectedPaymentMethod().getPaymentMethodType() == PaymentMethodModel.PaymentMethodType.TRANSFER){
                            createOrder(null);
                        }
                        else if(createOrderActivity.getSelectedPaymentMethod().getPaymentMethodType() == PaymentMethodModel.PaymentMethodType.TWINT) {
                            DialogHelper.hideLoadingDialog();
                            startTwintPayment();
                        }
                        else {
                            DialogHelper.hideLoadingDialog();
                            startBraintreePayment();
                        }
                        */


                    }
                });
    }

    private void showRestaurantOutOfOrderDialog(String message){

        DialogHelper.showTwoButtonsDialog(
                alertText,
                message,
                R.string.ok,
                new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        showDatePickerDialog();
                    }
                },
                R.string.cancel_all_caps,
                new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                }
        );
    }

    private void showDatePickerDialog() {

        Calendar nowDate = Calendar.getInstance();
        Calendar maxdate = Calendar.getInstance();
        maxdate.add(Calendar.DAY_OF_YEAR, 7);
        //maxdate.add(Calendar.MONTH, 1);

        int nowYear = nowDate.get(Calendar.YEAR);
        int nowMonth = nowDate.get(Calendar.MONTH);
        int nowDay = nowDate.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

                        String yearOfOrder = String.valueOf(year);
                        String monthOfOrder = String.valueOf(monthOfYear + 1);
                        String dayOfOrder = String.valueOf(dayOfMonth);

                        if(monthOfOrder.length() == 1){
                            monthOfOrder = "0" + monthOfOrder;
                        }

                        if(dayOfOrder.length() == 1){
                            dayOfOrder = "0" + dayOfOrder;
                        }

                        dateOfOrder = Calendar.getInstance();
                        dateOfOrder.set(year, monthOfYear, dayOfMonth);

                        dateOfOrderString = dayOfOrder + "-" + monthOfOrder + "-" + yearOfOrder;
                        showTimePickerDialog();
                    }
                },
                nowYear,
                nowMonth,
                nowDay
        );

        datePickerDialog.vibrate(false);
        datePickerDialog.setMinDate(nowDate);
        datePickerDialog.setMaxDate(maxdate);
        //datePickerDialog.autoDismiss(true);
        datePickerDialog.show(BaseActivity.currentActivity.getFragmentManager(), choosetext);
    }

    private void showTimePickerDialog(){

        Calendar nowDate = Calendar.getInstance();
        int nowHour = nowDate.get(Calendar.HOUR_OF_DAY);
        int nowMinute = nowDate.get(Calendar.MINUTE);
        int nowSecond = nowDate.get(Calendar.SECOND);

        int selectedDayIndex = dateOfOrder.get(Calendar.DAY_OF_WEEK);
        StoreWorkDayModel storeWorkDayModelOfSelectedDay = new StoreWorkDayModel();
        switch (selectedDayIndex){
            case 1:
                storeWorkDayModelOfSelectedDay = storeShiftModel.getSundayShift();
                break;
            case 2:
                storeWorkDayModelOfSelectedDay = storeShiftModel.getMondayShift();
                break;
            case 3:
                storeWorkDayModelOfSelectedDay = storeShiftModel.getTuesdayShift();
                break;
            case 4:
                storeWorkDayModelOfSelectedDay = storeShiftModel.getWednesdayShift();
                break;
            case 5:
                storeWorkDayModelOfSelectedDay = storeShiftModel.getThursdayShift();
                break;
            case 6:
                storeWorkDayModelOfSelectedDay = storeShiftModel.getFridayShift();
                break;
            case 7:
                storeWorkDayModelOfSelectedDay = storeShiftModel.getSaturdayShift();
                break;
        }


        TimePickerDialog timePickerDialog =
                TimePickerDialog.newInstance(
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {

                                String hourOfOrder = String.valueOf(hourOfDay);
                                String minuteOfOrder = String.valueOf(minute);

                                if(hourOfOrder.length() == 1){
                                    hourOfOrder = "0" + hourOfOrder;
                                }

                                if(minuteOfOrder.length() == 1){
                                    minuteOfOrder = "0" + minuteOfOrder;
                                }

                                timeOfOrder = hourOfOrder + ":" + minuteOfOrder;
                                checkDeliveryTimeWithDateAndTime();
                                //redirectToPayment();
                            }
                        },
                        nowHour,
                        nowMinute,
                        true
                );



        int shiftStartHour = Integer.valueOf(storeWorkDayModelOfSelectedDay.getShiftStartTime().substring(0,2));
        int shiftStartMinute = Integer.valueOf(storeWorkDayModelOfSelectedDay.getShiftStartTime().substring(3, 5));
        int shiftEndHour = Integer.valueOf(storeWorkDayModelOfSelectedDay.getShiftEndTime().substring(0,2));
        int shiftEndMinute = Integer.valueOf(storeWorkDayModelOfSelectedDay.getShiftEndTime().substring(3, 5));

        //timePickerDialog.setMinTime(new Timepoint(shiftStartHour, shiftStartMinute));
        //timePickerDialog.setMaxTime(new Timepoint(shiftEndHour, shiftEndMinute));
        timePickerDialog.setSelectableTimes(generateEnabledTimePoints(storeWorkDayModelOfSelectedDay));

        timePickerDialog.vibrate(false);
        //timePickerDialog.setMinTime(nowHour, nowMinute, nowSecond);
        timePickerDialog.show(BaseActivity.currentActivity.getFragmentManager(), choosetext);
    }

    private void redirectToPayment(){
        if(createOrderActivity.getSelectedPaymentMethod().getPaymentMethodType() == PaymentMethodModel.PaymentMethodType.UNKNOWN){
            DialogHelper.hideLoadingDialog();
            DialogHelper.showAlertDialog(BaseActivity.currentActivity, unknownPaymentMethodText);
        }
        else if(createOrderActivity.getSelectedPaymentMethod().getPaymentMethodType() == PaymentMethodModel.PaymentMethodType.CASH ||
                createOrderActivity.getSelectedPaymentMethod().getPaymentMethodType() == PaymentMethodModel.PaymentMethodType.TRANSFER){
            createOrder(null);
        }
        /*
        else if(createOrderActivity.getSelectedPaymentMethod().getPaymentMethodType() == PaymentMethodModel.PaymentMethodType.TWINT) {
            DialogHelper.hideLoadingDialog();
            startTwintPayment();
        }
        */
        else {
            DialogHelper.hideLoadingDialog();
            startBraintreePayment();
        }
    }

    private void createOrder(String paymentMethodNonce){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<Integer>> call = ApiService.apiInterface.createOrder(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_CREATE_ORDER + SessionHelper.getCustomerToken().getToken(), getCreateOrderParams(paymentMethodNonce));
        call.enqueue(new Callback<ResponseObject<Integer>>() {
            @Override
            public void onResponse(Call<ResponseObject<Integer>> call, Response<ResponseObject<Integer>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() && response.body().isSuccess()){
                    createOrderActivity.onNextClicked(FRAGMENT_NAME);
                }
                else{
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private HashMap<String, Object> getCreateOrderParams(String paymentMethodNonce){
        HashMap<String, Object> params = new HashMap<>();
        params.put("customer_id", SessionHelper.getUser().getId());
        params.put("shipping_method_title", createOrderActivity.getSelectedShippingMethod().getTitle());
        params.put("shipping_method_code", createOrderActivity.getSelectedShippingMethod().getCode());
        params.put("address_id", createOrderActivity.getSelectedShippingAddress().getId());
        params.put("payment_method_title", createOrderActivity.getSelectedPaymentMethod().getTitle());
        params.put("payment_method_code", createOrderActivity.getSelectedPaymentMethod().getCode());
        params.put("comment", createOrderNote());
        params.put("is_pizza_pass_campaign", createOrderActivity.getCartInfo().isPizzapassCampaignUsed());
        params.put("is_champagne_campaign", createOrderActivity.getCartInfo().isChampagneCampaignUsed());
        if(paymentMethodNonce != null){
            params.put("payment_method_nonce", paymentMethodNonce);
        }
        return params;
    }

    private String createOrderNote(){

        CreateOrderActivity createOrderActivity = (CreateOrderActivity) getActivity();
        StringBuilder stringBuilder = new StringBuilder();
        if(isCartContainsAnyPizza()){
            stringBuilder.append(slicePizzaForStoreText).append(" : ");
            if(createOrderActivity.getSlicePizza()){
                stringBuilder.append(yesText);
            }
            else {
                stringBuilder.append(noText);
            }
            stringBuilder.append("\n");
        }

        stringBuilder
                .append(createOrderActivity.getOrderNote())
                .append("\n");

        if(dateOfOrderString != null && !dateOfOrderString.isEmpty() &&
                timeOfOrder != null && !timeOfOrder.isEmpty()){

            stringBuilder
                    .append(deliveryDateText)
                    .append(" ")
                    .append(dateOfOrderString)
                    .append("\n")
                    .append(deliveryTimeText)
                    .append(" ")
                    .append(timeOfOrder);

        }

        if(stringBuilder.toString().equals("\n") || stringBuilder.toString().equals("\n<br/>") || stringBuilder.toString().equals("<br/>")){
            return "";
        }
        else {
            return stringBuilder.toString();
        }
    }

    private boolean isCartContainsAnyPizza(){
        boolean containsAnyPizza = false;
        outerloop:
        for(CartProductModel cartProductModel : createOrderActivity.getCartInfo().getProducts()){
            if(SharedPrefsHelper.readPizzaCategoryIdList().contains(Integer.valueOf(cartProductModel.getProductId()))){
                containsAnyPizza = true;
                break;
            }
            for(String categoryId : cartProductModel.getCategoryList()){
                if(SharedPrefsHelper.readPizzaCategoryIdList().contains(Integer.valueOf(categoryId))){
                    containsAnyPizza = true;
                    break outerloop;
                }
            }
        }
        return containsAnyPizza;
    }

    private void getCartProducts(){
        DialogHelper.showLoadingDialog();
        /*
        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken());
                */
        HashMap<String, Object> params = new HashMap<>();
        if(SessionHelper.getSelectedCoupon() != null){
            params.put("coupon", SessionHelper.getSelectedCoupon().getCode());
        }

        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken(),
                params);

        call.enqueue(new Callback<ResponseObject<CartInfoModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<CartInfoModel>> call, Response<ResponseObject<CartInfoModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    response.body().getData().checkNull();
                    createOrderActivity.setCartInfo(response.body().getData());
                }
                else
                    ApiErrorUtils.parseError(response);
            }

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

    private void getCartProductsWithCommission(){
        DialogHelper.showLoadingDialog();
        /*
        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProductsForCommission(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken(),
                createOrderActivity.getSelectedPaymentMethod().getCode(),
                createOrderActivity.getSelectedShippingMethod().getCode());
                */

        HashMap<String, Object> params = new HashMap<>();
        if(SessionHelper.getSelectedCoupon() != null){
            params.put("coupon", SessionHelper.getSelectedCoupon().getCode());
        }
        params.put("payment_method", createOrderActivity.getSelectedPaymentMethod().getCode());
        params.put("shipping_method",createOrderActivity.getSelectedShippingMethod().getCode());

        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken(),
                params);

        call.enqueue(new Callback<ResponseObject<CartInfoModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<CartInfoModel>> call, Response<ResponseObject<CartInfoModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    CartInfoModel cartInfoModel = response.body().getData();
                    cartInfoModel.checkNull();
                    createOrderActivity.setCartInfo(cartInfoModel);
                    //setOrderTotalText(response.body().getData());
                    cartTotalList.clear();
                    cartTotalList.addAll(cartInfoModel.getTotalsList());
                    orderPriceRecyclerAdapter.notifyDataSetChanged();
                }
                else
                    ApiErrorUtils.parseError(response);
            }

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

    private void startBraintreePayment(){

        // CVV kodu default olarak gozukmuyor.
        // Gozukmesi için braintree'ye login ol
        // Go to Settings --> Processing --> CVV --> Click on Edit --> Check option 'CVV not provided(l)', Enable option 'for any transaction'

        DropInRequest paymentRequest = new DropInRequest()
                //.tokenizationKey(ApiConstants.BRAINTREE_TOKENIZATION_KEY_SANDBOX)
                .tokenizationKey(ApiConstants.BRAINTREE_TOKENIZATION_KEY_PRODUCTION)
                //.clientToken("eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiI3NzY2ZmNmNTQ3MDc1YWMzMGZiNmIxMzU3MTI1ZTJmODc5YjM4MmNkOTcwYmYwZmYyNmQzMWJmNGRiYjI1MjQzfGNyZWF0ZWRfYXQ9MjAxOC0wNi0xM1QxODo1Mzo0Mi4wODA4MDc5MDQrMDAwMFx1MDAyNm1lcmNoYW50X2lkPTM0OHBrOWNnZjNiZ3l3MmJcdTAwMjZwdWJsaWNfa2V5PTJuMjQ3ZHY4OWJxOXZtcHIiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tOjQ0My9tZXJjaGFudHMvMzQ4cGs5Y2dmM2JneXcyYi9jbGllbnRfYXBpL3YxL2NvbmZpZ3VyYXRpb24iLCJjaGFsbGVuZ2VzIjpbXSwiZW52aXJvbm1lbnQiOiJzYW5kYm94IiwiY2xpZW50QXBpVXJsIjoiaHR0cHM6Ly9hcGkuc2FuZGJveC5icmFpbnRyZWVnYXRld2F5LmNvbTo0NDMvbWVyY2hhbnRzLzM0OHBrOWNnZjNiZ3l3MmIvY2xpZW50X2FwaSIsImFzc2V0c1VybCI6Imh0dHBzOi8vYXNzZXRzLmJyYWludHJlZWdhdGV3YXkuY29tIiwiYXV0aFVybCI6Imh0dHBzOi8vYXV0aC52ZW5tby5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tIiwiYW5hbHl0aWNzIjp7InVybCI6Imh0dHBzOi8vb3JpZ2luLWFuYWx5dGljcy1zYW5kLnNhbmRib3guYnJhaW50cmVlLWFwaS5jb20vMzQ4cGs5Y2dmM2JneXcyYiJ9LCJ0aHJlZURTZWN1cmVFbmFibGVkIjp0cnVlLCJwYXlwYWxFbmFibGVkIjp0cnVlLCJwYXlwYWwiOnsiZGlzcGxheU5hbWUiOiJBY21lIFdpZGdldHMsIEx0ZC4gKFNhbmRib3gpIiwiY2xpZW50SWQiOm51bGwsInByaXZhY3lVcmwiOiJodHRwOi8vZXhhbXBsZS5jb20vcHAiLCJ1c2VyQWdyZWVtZW50VXJsIjoiaHR0cDovL2V4YW1wbGUuY29tL3RvcyIsImJhc2VVcmwiOiJodHRwczovL2Fzc2V0cy5icmFpbnRyZWVnYXRld2F5LmNvbSIsImFzc2V0c1VybCI6Imh0dHBzOi8vY2hlY2tvdXQucGF5cGFsLmNvbSIsImRpcmVjdEJhc2VVcmwiOm51bGwsImFsbG93SHR0cCI6dHJ1ZSwiZW52aXJvbm1lbnROb05ldHdvcmsiOnRydWUsImVudmlyb25tZW50Ijoib2ZmbGluZSIsInVudmV0dGVkTWVyY2hhbnQiOmZhbHNlLCJicmFpbnRyZWVDbGllbnRJZCI6Im1hc3RlcmNsaWVudDMiLCJiaWxsaW5nQWdyZWVtZW50c0VuYWJsZWQiOnRydWUsIm1lcmNoYW50QWNjb3VudElkIjoiYWNtZXdpZGdldHNsdGRzYW5kYm94IiwiY3VycmVuY3lJc29Db2RlIjoiVVNEIn0sIm1lcmNoYW50SWQiOiIzNDhwazljZ2YzYmd5dzJiIiwidmVubW8iOiJvZmYifQ==")
                //.amount("CHF1.0")
                //.requestThreeDSecureVerification(true)
                .disableAndroidPay()
                .disableVenmo();


        /*
        switch (createOrderActivity.getSelectedPaymentMethod().getPaymentMethodType()){
            case CREDIT_DEBIT_CARD:
                paymentRequest.disableAndroidPay();
                paymentRequest.disablePayPal();
                break;
            case PAYPAL:
                paymentRequest.disableAndroidPay();
                break;
            case ANDROID_PAY:
                paymentRequest.disablePayPal();
                if(getAndroidPayCart() == null){
                    DialogHelper.showAlertDialog(BaseActivity.currentActivity, androidPayNotFoundText);
                    return;
                }
                else {
                    paymentRequest.androidPayCart(getAndroidPayCart());
                }
                break;
        }
        */
        startActivityForResult(paymentRequest.getIntent(BaseActivity.currentActivity), REQUEST_CODE_BRAINTREE_PAYMENT);
    }

    private void startTwintPayment(){

    }

    private void createBraintreePayment(final DropInResult dropInResult){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject> call = ApiService.apiInterface.createPayment(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_CREATE_PAYMENT + SessionHelper.getCustomerToken().getToken(),
                getBraintreePaymentParams(dropInResult));
        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()){
                    createOrder(dropInResult.getPaymentMethodNonce().getNonce());
                }
                else {
                    ApiErrorUtils.parseError(response);
                    /*
                     // dummy //
                    createOrder(dropInResult.getPaymentMethodNonce().getNonce());
                    */
                }
            }

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

    private HashMap<String, Object> getBraintreePaymentParams(DropInResult dropInResult){
        HashMap<String, Object> params = new HashMap<>();
        params.put("payment_method_nonce", dropInResult.getPaymentMethodNonce().getNonce());
        params.put("amount", PriceHelper.removeCurrencyFromPrice(createOrderActivity.getCartInfo().getCartTotalModel().getText()));
        return params;
    }

    private Cart getAndroidPayCart() {
        return Cart.newBuilder()
                .setCurrencyCode("CHF")
                .setTotalPrice(PriceHelper.removeCurrencyFromPrice(createOrderActivity.getCartInfo().getCartTotalModel().getText()))
                /*
                .addLineItem(LineItem.newBuilder()
                        .setCurrencyCode("CHF")
                        .setDescription("Description")
                        .setQuantity("1")
                        .setUnitPrice("1.00")
                        .setTotalPrice("1.00")
                        .build())
                        */
                .build();
    }

    /*
    private void setOrderTotalText(CartInfoModel cartInfoModel){

        CartTotalModel subtotalModel = new CartTotalModel("","");
        CartTotalModel commissionModel = new CartTotalModel("","");
        CartTotalModel totalModel = new CartTotalModel("","");

        String totalText = "";

        for (CartTotalModel cartTotalModel : cartInfoModel.getTotalsList()){
            switch (cartTotalModel.getTitle().toLowerCase()){
                case ApiConstants.CART_SUBTOTAL :
                    subtotalModel = cartTotalModel;
                    break;
                case ApiConstants.CART_COMMISSION :
                    commissionModel = cartTotalModel;
                    break;
                case ApiConstants.CART_TOTAL :
                    totalModel = cartTotalModel;
                    break;
            }
        }

        if(commissionModel.getText().isEmpty()){
            totalText = PriceHelper.roundFractions(cartInfoModel.getCartTotalModel().getText());
        }
        else {
            totalText =
                    new StringBuilder()
                            .append(subtotalModel.getTitle())
                            .append("\n")
                            .append(subtotalModel.getText())
                            .append("\n\n")
                            .append(commissionModel.getTitle())
                            .append("\n")
                            .append(commissionModel.getText())
                            .append("\n\n")
                            .append(totalModel.getTitle())
                            .append("\n")
                            .append(totalModel.getText())
                            //.append(PriceHelper.roundFractions(totalModel.getText()))
                            .toString();
        }
        //orderTotalPizzalinkInfoLayout.setText(totalText);

    }
    */

    /*
    private Timepoint[] generateDisabledTimePoints(StoreWorkDayModel storeWorkDayModelOfSelectedDay){

        int breakStartHour = Integer.valueOf(storeWorkDayModelOfSelectedDay.getBreakStartTime().substring(0,2));
        int breakStartMinute = Integer.valueOf(storeWorkDayModelOfSelectedDay.getBreakStartTime().substring(3, 5));
        int breakEndHour = Integer.valueOf(storeWorkDayModelOfSelectedDay.getBreakEndTime().substring(0,2));
        int breakEndMinute = Integer.valueOf(storeWorkDayModelOfSelectedDay.getBreakEndTime().substring(3, 5));

        int hour = breakStartHour;
        int minute = breakStartMinute;

        ArrayList<Timepoint> disabledTimePointList = new ArrayList<>();

        while (hour <= breakEndHour && minute <= breakEndMinute){
            disabledTimePointList.add(new Timepoint(hour, minute));
            Log.i("vrjgerureg", "" + hour + ":" + minute);
            minute++;
            if(minute == 60){
                minute = 0;
                hour += 1;
            }
        }

        return disabledTimePointList.toArray(new Timepoint[disabledTimePointList.size()]);
    }
    */

    private Timepoint[] generateEnabledTimePoints(StoreWorkDayModel storeWorkDayModelOfSelectedDay){

        int shiftStartHour = Integer.valueOf(storeWorkDayModelOfSelectedDay.getShiftStartTime().substring(0,2));
        int shiftStartMinute = Integer.valueOf(storeWorkDayModelOfSelectedDay.getShiftStartTime().substring(3, 5));
        int shiftEndHour = Integer.valueOf(storeWorkDayModelOfSelectedDay.getShiftEndTime().substring(0,2));
        int shiftEndMinute = Integer.valueOf(storeWorkDayModelOfSelectedDay.getShiftEndTime().substring(3, 5));

        int breakStartHour = Integer.valueOf(storeWorkDayModelOfSelectedDay.getBreakStartTime().substring(0,2));
        int breakStartMinute = Integer.valueOf(storeWorkDayModelOfSelectedDay.getBreakStartTime().substring(3, 5));
        int breakEndHour = Integer.valueOf(storeWorkDayModelOfSelectedDay.getBreakEndTime().substring(0,2));
        int breakEndMinute = Integer.valueOf(storeWorkDayModelOfSelectedDay.getBreakEndTime().substring(3, 5));

        int hour = shiftStartHour;
        int minute = shiftStartMinute;

        ArrayList<Timepoint> enabledTimePointList = new ArrayList<>();

        // öğleden tatilinden önceki kısım
        while (hour <= breakStartHour){
            enabledTimePointList.add(new Timepoint(hour, minute));
            minute++;
            if(minute == 60){
                minute = 0;
                hour += 1;
            }

            if(hour == breakStartHour && minute == breakStartMinute){
                break;
            }
        }

        // öğle tatilinden sonraki kısım
        if(breakEndMinute == 59){
            breakEndMinute = 0;
            breakEndHour += 1;
        }

        hour = breakEndHour;
        minute = breakEndMinute;


        while (hour <= shiftEndHour){
            enabledTimePointList.add(new Timepoint(hour, minute));
            minute++;
            if(minute == 60){
                minute = 0;
                hour += 1;
            }

            if(hour == shiftEndHour && minute == shiftEndMinute){
                break;
            }
        }

        return enabledTimePointList.toArray(new Timepoint[enabledTimePointList.size()]);
    }

}
