package ch.pizzalemon.android.activity;

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

import java.util.HashMap;

import butterknife.BindString;
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.SharedPrefsHelper;
import ch.pizzalemon.android.helper.ViewHelper;
import ch.pizzalemon.android.model.AddressModel;
import ch.pizzalemon.android.model.CustomerTokenModel;
import ch.pizzalemon.android.model.UserModel;
import ch.pizzalemon.android.model.cart.CartInfoModel;
import ch.pizzalemon.android.view.AppEditText;
import ch.pizzalemon.android.view.AppToolbar;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.loginAppToolbar) AppToolbar loginAppToolbar;
    @BindView(R.id.emailPizzalinkEditText) AppEditText emailAppEditText;
    @BindView(R.id.passwordPizzalinkEditText) AppEditText passwordAppEditText;
    @BindView(R.id.loginButton) Button loginButton;
    @BindView(R.id.forgotPasswordTextView) TextView forgotPasswordTextView;

    @BindString(R.string.forgot_password_hint) String forgotPasswordHintText;
    @BindString(R.string.reset_password) String resetPasswordText;

    @BindString(R.string.not_have_an_accaount) String notHaveAnAccountText;
    @BindString(R.string.register_text) String registerText;
    @BindString(R.string.alert_fill_all_fields) String fillAllFieldsText;
    @BindString(R.string.alert_invalid_email) String validEmailText;

    private boolean showBackIcon;

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

    @OnClick({R.id.loginButton, R.id.forgotPasswordTextView,
            R.id.registerButton, R.id.loginAsGuestTextView})
    protected void onClick(View view){
        switch (view.getId()){
            case R.id.loginButton:
                ViewHelper.hideKeyboard();
                if(checkFields())
                    login();
                break;
            case R.id.forgotPasswordTextView:
                startActivity(new Intent(LoginActivity.this, ForgotPasswordActivity.class));
                break;
            case R.id.registerButton:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                break;
            case R.id.loginAsGuestTextView:
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                break;
        }
    }

    private void getDataFromIntent(){
        showBackIcon = getIntent().getBooleanExtra("showBackIcon", false);
    }

    private void initViews(){
        loginAppToolbar.setBackIconVisibility(showBackIcon);
    }

    private boolean checkFields(){

        if(emailAppEditText.isEmpty() || passwordAppEditText.isEmpty()){
            DialogHelper.showAlertDialog(this, fillAllFieldsText);
            return false;
        }

        if(!emailAppEditText.isEmail()){
            DialogHelper.showAlertDialog(this, validEmailText);
            return false;
        }

        return true;
    }

    private void login(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<UserModel>> call = ApiService.apiInterface.login(
                SessionHelper.getSelectedStore().getStoreName(),
                emailAppEditText.getText(), passwordAppEditText.getText());
        call.enqueue(new Callback<ResponseObject<UserModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<UserModel>> call, Response<ResponseObject<UserModel>> response) {
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    SharedPrefsHelper.saveUser(response.body().getData());
                    CustomerTokenModel customerTokenModel = response.body().getData().getToken();
                    customerTokenModel.setStoreOfToken(SessionHelper.getSelectedStore());
                    SharedPrefsHelper.saveCustomerToken(customerTokenModel);
                    SharedPrefsHelper.setCustomerLoggedIn(true);
                    getCartItemCount();
                }
                else{
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseErrorWithoutAuthorizationErrorControl(response);
                }
            }

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

    private void getCartItemCount(){
        /*
        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken());
                */

        HashMap<String, Object> params = new HashMap<>();
        SessionHelper.addCouponCodeToRequestParamsIfNeeded(params);

        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()){
                    SharedPrefsHelper.setCartItemCount(response.body().getData().getProducts().size());
                    SharedPrefsHelper.setCartTotalPrice(PriceHelper.removeCurrencyFromPrice(response.body().getData().getCartTotalModel().getText()));
                    getUserAddress();

                }
                else
                    ApiErrorUtils.parseError(response);
            }

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

    private void getUserAddress(){
        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()){
                    if (!response.body().getData().isEmpty()){
                        SessionHelper.saveUserMainAddress(response.body().getData().get(0));
                    }
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finishAffinity();
                }
                else {
                    ApiErrorUtils.parseError(response);
                }
            }

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

}
