package ch.pizzalink.android.activity;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
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.pizzalink.android.R;
import ch.pizzalink.android.api.ApiEndPoints;
import ch.pizzalink.android.api.ApiErrorUtils;
import ch.pizzalink.android.api.ApiService;
import ch.pizzalink.android.api.ResponseObject;
import ch.pizzalink.android.helper.DialogHelper;
import ch.pizzalink.android.helper.SessionHelper;
import ch.pizzalink.android.model.UserModel;
import ch.pizzalink.android.view.PizzalinkEditText;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UpdateProfileActivity extends BaseActivity {

    @BindView(R.id.firstnamePizzalinkEditText) PizzalinkEditText firstnamePizzalinkEditText;
    @BindView(R.id.lasstnamePizzalinkEditText) PizzalinkEditText lasstnamePizzalinkEditText;
    @BindView(R.id.telephonePizzalinkEditText) PizzalinkEditText telephonePizzalinkEditText;
    @BindView(R.id.emailPizzalinkEditText) PizzalinkEditText emailPizzalinkEditText;
    @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(){
        firstnamePizzalinkEditText.setText(userModel.getFirstname());
        lasstnamePizzalinkEditText.setText(userModel.getLastname());
        telephonePizzalinkEditText.setText(userModel.getTelephone());
        emailPizzalinkEditText.setText(userModel.getEmail());
    }

    private void updateProfile(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<UserModel>> call = ApiService.apiInterface.updateProfile(
                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", firstnamePizzalinkEditText.getText());
        params.put("lastname", lasstnamePizzalinkEditText.getText());
        params.put("email", emailPizzalinkEditText.getText());
        params.put("telephone", telephonePizzalinkEditText.getText());
        return params;
    }

    private boolean checkFields(){

        if(firstnamePizzalinkEditText.isEmpty() ||
                lasstnamePizzalinkEditText.isEmpty() ||
                telephonePizzalinkEditText.isEmpty() ||
                emailPizzalinkEditText.isEmpty()){
            DialogHelper.showAlertDialog(BaseActivity.currentActivity, fillAllFieldsText);
            return false;
        }

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

        return true;
    }

}
