package ch.pizzapp.android.activity;

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

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.pizzapp.android.R;
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.helper.ViewHelper;
import ch.pizzapp.android.model.UserModel;
import ch.pizzapp.android.model.cart.CartInfoModel;
import ch.pizzapp.android.view.AppEditText;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends BaseActivity {

    @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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        //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 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(
                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());
                    SharedPrefsHelper.saveCustomerToken(response.body().getData().getToken());
                    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(
                ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken());
        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()));
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finishAffinity();

                }
                else
                    ApiErrorUtils.parseError(response);
            }

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