package ch.pizzalemon.android.activity;

import androidx.annotation.NonNull;
import android.os.Bundle;
import android.widget.Button;

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

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.ResponseObject;
import ch.pizzalemon.android.helper.DialogHelper;
import ch.pizzalemon.android.helper.SessionHelper;
import ch.pizzalemon.android.model.UserModel;
import ch.pizzalemon.android.view.AppEditText;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UpdateProfileActivity extends BaseActivity {

    @BindView(R.id.firstnamePizzalinkEditText)
    AppEditText firstnameAppEditText;
    @BindView(R.id.lasstnamePizzalinkEditText)
    AppEditText lasstnameAppEditText;
    @BindView(R.id.telephonePizzalinkEditText)
    AppEditText telephoneAppEditText;
    @BindView(R.id.emailPizzalinkEditText)
    AppEditText emailAppEditText;
    @BindView(R.id.updateProfileButton) Button updateProfileButton;

    @BindString(R.string.alert_fill_all_fields) String fillAllFieldsText;
    @BindString(R.string.alert_invalid_email) String validEmailText;
    @BindString(R.string.profile_updated) String profileUpdatedText;

    private UserModel userModel;

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

    @OnClick(R.id.updateProfileButton)
    public void onClick(){
        if(checkFields())
            updateProfile();
    }

    private void getDataFromIntent(){
        userModel = (UserModel) getIntent().getSerializableExtra("userModel");
    }

    private void setFields(){
        firstnameAppEditText.setText(userModel.getFirstname());
        lasstnameAppEditText.setText(userModel.getLastname());
        telephoneAppEditText.setText(userModel.getTelephone());
        emailAppEditText.setText(userModel.getEmail());
    }

    private void updateProfile(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<UserModel>> call = ApiService.apiInterface.updateProfile(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_UPDATE_PROFILE + SessionHelper.getCustomerToken().getToken(),
                getUpdateProfileParams());
        call.enqueue(new Callback<ResponseObject<UserModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<UserModel>> call, final Response<ResponseObject<UserModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    SessionHelper.saveCustomer(response.body().getData());
                    DialogHelper.showOneButtonDialogWithCallback(profileUpdatedText, new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            setResult(RESULT_OK);
                            finish();
                        }
                    });
                }
                else {
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private HashMap<String, Object> getUpdateProfileParams(){
        HashMap<String, Object> params = new HashMap<>();
        params.put("firstname", firstnameAppEditText.getText());
        params.put("lastname", lasstnameAppEditText.getText());
        params.put("email", emailAppEditText.getText());
        params.put("telephone", telephoneAppEditText.getText());
        return params;
    }

    private boolean checkFields(){

        if(firstnameAppEditText.isEmpty() ||
                lasstnameAppEditText.isEmpty() ||
                telephoneAppEditText.isEmpty() ||
                emailAppEditText.isEmpty()){
            DialogHelper.showAlertDialog(BaseActivity.currentActivity, fillAllFieldsText);
            return false;
        }

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

        return true;
    }

}
