package ch.pizzalemon.android.fragment.createOrder;

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 android.widget.Button;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.pizzalemon.android.R;
import ch.pizzalemon.android.activity.AddAddressActivity;
import ch.pizzalemon.android.activity.BaseActivity;
import ch.pizzalemon.android.activity.CreateOrderActivity;
import ch.pizzalemon.android.adapter.recycler.ShippingAddressesRecyclerAdapter;
import ch.pizzalemon.android.api.ApiConstants;
import ch.pizzalemon.android.api.ApiErrorUtils;
import ch.pizzalemon.android.api.ApiService;
import ch.pizzalemon.android.api.ResponseArray;
import ch.pizzalemon.android.helper.DialogHelper;
import ch.pizzalemon.android.helper.SessionHelper;
import ch.pizzalemon.android.interfaces.RecyclerItemClickListener;
import ch.pizzalemon.android.model.AddressModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;

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

public class ShippingAddressFragment extends CreateOrderBaseFragment {

    @BindView(R.id.shippingAddressesRecyclerView) RecyclerView shippingAddressesRecyclerView;
    @BindView(R.id.addNewAddressButton) Button addNewAddressButton;

    @BindString(R.string.alert_choose_shipping_address) String chooseShippingAddressText;

    private ArrayList<AddressModel> addressList = new ArrayList<>();
    private ShippingAddressesRecyclerAdapter shippingAddressesRecyclerAdapter;
    private AddressModel selectedAddress;
    private int REQUEST_CODE_ADD_NEW_ADDRESS = 2350;
    private boolean needToSortAddresses;
    private String newAddressId = "";

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

    public ShippingAddressFragment() {}

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

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

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE_ADD_NEW_ADDRESS &&
                resultCode == RESULT_OK){
            newAddressId = data.getStringExtra("newAddressId");
            getCustomerShippingAddresses();
        }
    }

    @OnClick({R.id.addNewAddressButton, R.id.previousTextView, R.id.nextTextView})
    protected void onClick(View view){
        CreateOrderActivity createOrderActivity = (CreateOrderActivity) BaseActivity.currentActivity;
        switch (view.getId()){
            case R.id.addNewAddressButton:
                Intent addNewAddressIntent = new Intent(BaseActivity.currentActivity,
                        AddAddressActivity.class);
                startActivityForResult(addNewAddressIntent, REQUEST_CODE_ADD_NEW_ADDRESS);
                break;
            case R.id.previousTextView:
                createOrderActivity.onPreviousClicked(FRAGMENT_NAME);
                break;
            case R.id.nextTextView:

                if(selectedAddress == null){
                    DialogHelper.showAlertDialog(BaseActivity.currentActivity, chooseShippingAddressText);
                    return;
                }

                createOrderActivity.setSelectedShippingAddress(selectedAddress);
                createOrderActivity.onNextClicked(FRAGMENT_NAME);
                break;
        }
    }

    private void initViews(){
        initRecyclerView();
        CreateOrderActivity createOrderActivity = (CreateOrderActivity) BaseActivity.currentActivity;
        if(createOrderActivity.getSelectedShippingMethod().getCode().toLowerCase().equals(ApiConstants.SHIPPING_METHOD_CODE_PICK_UP_FROM_STORE)){
            addNewAddressButton.setText(R.string.add_new_shipping_address_for_self_pick_up);
        }
        else {
            addNewAddressButton.setText(R.string.add_new_shipping_address_for_free_shipping);
        }
    }

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

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

    private void fillAndNotifyAdapter(ArrayList<AddressModel> addressModels){

        AddressModel.checkNull(addressModels);
        addressList.clear();
        addressList.addAll(addressModels);

        if(addressList.size() != 0){

            sortAddresses();

            CreateOrderActivity createOrderActivity = (CreateOrderActivity) BaseActivity.currentActivity;

            if(!newAddressId.isEmpty()){
                for(AddressModel addressModel : addressModels){
                    if(addressModel.getId().equals(newAddressId)){
                        addressModel.setSelected(true);
                        selectedAddress = addressModel;
                        createOrderActivity.setSelectedShippingAddress(addressModel);
                        break;
                    }
                }
            }
            else if(createOrderActivity.getSelectedShippingAddress() == null){
                addressList.get(0).setSelected(true);
                selectedAddress = addressList.get(0);
            }
            else {
                for(AddressModel addressModel : addressModels){
                    if(addressModel.getId().equals(createOrderActivity.getSelectedShippingAddress().getId())){
                        addressModel.setSelected(true);
                        selectedAddress = addressModel;
                        break;
                    }
                }
            }
        }

        shippingAddressesRecyclerAdapter.notifyDataSetChanged();
    }

    private void initRecyclerView(){
        shippingAddressesRecyclerAdapter = new ShippingAddressesRecyclerAdapter(addressList, new RecyclerItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                for(AddressModel addressModel : addressList){
                    addressModel.setSelected(false);
                }
                addressList.get(position).setSelected(true);
                selectedAddress = addressList.get(position);
                shippingAddressesRecyclerAdapter.notifyDataSetChanged();
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(BaseActivity.currentActivity);
        shippingAddressesRecyclerView.setLayoutManager(layoutManager);
        shippingAddressesRecyclerView.setAdapter(shippingAddressesRecyclerAdapter);
    }

    private void sortAddresses(){
        Collections.sort(
                addressList,
                new Comparator<AddressModel>() {
                    @Override
                    public int compare(AddressModel a1, AddressModel a2) {
                        try {
                            int id1 = Integer.parseInt(a1.getId());
                            int id2 = Integer.parseInt(a2.getId());
                            return id2 - id1;
                        }catch (Exception e){
                            return a2.getId().compareTo(a1.getId());
                        }
                    }
                }
        );
    }
}