package ch.pizzalemon.android.activity;

import android.content.Intent;
import androidx.annotation.NonNull;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

import java.util.ArrayList;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.pizzalemon.android.R;
import ch.pizzalemon.android.adapter.recycler.MyAddressesRecyclerAdapter;
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.AddressModel;
import ch.pizzalemon.android.model.DeleteAddressResponseModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MyAddressesActivity extends BaseActivity {

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

    @BindString(R.string.alert_delete_address) String deleteAddressAlertText;
    @BindString(R.string.address_deleted) String addressDeletedText;

    private ArrayList<AddressModel> addressList = new ArrayList<>();
    private MyAddressesRecyclerAdapter addressesRecyclerAdapter;
    private int REQUEST_CODE_ADD_NEW_ADDRESS = 8573;

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

    @OnClick(R.id.addNewAddressButton)
    public void onClick(){
        Intent addNewAddressIntent = new Intent(this, AddAddressActivity.class);
        startActivityForResult(addNewAddressIntent, REQUEST_CODE_ADD_NEW_ADDRESS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE_ADD_NEW_ADDRESS &&
                resultCode == RESULT_OK){
            getCustomerAddresses();
        }
    }

    private void initViews(){
        initRecyclerView();
    }

    private void getCustomerAddresses(){
        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.isEmpty()) {
            SessionHelper.saveUserMainAddress(addressList.get(0));
        }
        addressesRecyclerAdapter.notifyDataSetChanged();
    }

    private void initRecyclerView(){
        addressesRecyclerAdapter = new MyAddressesRecyclerAdapter(addressList, new RecyclerItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {
                DialogHelper.showTwoButtonsDialog(BaseActivity.currentActivity, deleteAddressAlertText,
                        new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                deleteAddress(position);
                            }
                        },
                        new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        });
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(BaseActivity.currentActivity);
        myAddressesRecyclerView.setLayoutManager(layoutManager);
        myAddressesRecyclerView.setAdapter(addressesRecyclerAdapter);
    }

    private void deleteAddress(final int position){
        DialogHelper.hideLoadingDialog();
        Call<ResponseObject<DeleteAddressResponseModel>> call = ApiService.apiInterface.deleteAddress(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_DELETE_ADDRESS + SessionHelper.getCustomerToken().getToken(),
                addressList.get(position).getId());
        call.enqueue(new Callback<ResponseObject<DeleteAddressResponseModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<DeleteAddressResponseModel>> call, Response<ResponseObject<DeleteAddressResponseModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body() != null &&
                        response.body().isSuccess()){
                    DialogHelper.showDialogWithPositiveButton(BaseActivity.currentActivity, addressDeletedText);
                    addressList.remove(position);
                    addressesRecyclerAdapter.notifyDataSetChanged();
                }
                else {
                    ApiErrorUtils.parseError(response);
                }
            }

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