package ch.pizzalink.android.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;

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

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.pizzalink.android.R;
import ch.pizzalink.android.activity.BaseActivity;
import ch.pizzalink.android.activity.LoginActivity;
import ch.pizzalink.android.activity.MyAddressesActivity;
import ch.pizzalink.android.activity.UpdatePasswordActivity;
import ch.pizzalink.android.activity.UpdateProfileActivity;
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.helper.SharedPrefsHelper;
import ch.pizzalink.android.model.UserModel;
import ch.pizzalink.android.view.PizzalinkInfoView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;

/**
 * Created by cimenmus on 18/09/2017.
 */

public class ProfileFragment extends BaseFragment {

    @BindView(R.id.firstnamePizzalinkInfoLayout) PizzalinkInfoView firstnamePizzalinkInfoLayout;
    @BindView(R.id.lastnamePizzalinkInfoLayout) PizzalinkInfoView lastnamePizzalinkInfoLayout;
    @BindView(R.id.emailPizzalinkInfoLayout) PizzalinkInfoView emailPizzalinkInfoLayout;
    @BindView(R.id.phonePizzalinkInfoLayout) PizzalinkInfoView phonePizzalinkInfoLayout;
    @BindView(R.id.myAddressesLayout) RelativeLayout myAddressesLayout;
    @BindView(R.id.updateProfileLayout) RelativeLayout updateProfileLayout;
    @BindView(R.id.updatePasswordLayout) RelativeLayout updatePasswordLayout;
    @BindView(R.id.logoutLayout) RelativeLayout logoutLayout;

    @BindString(R.string.bottom_nav_menu_item_profile) String fragmentTitle;
    @BindString(R.string.alert_logout) String logoutAlertText;

    public static final java.lang.String FRAGMENT_NAME = "profileFragment";
    private int REQUEST_CODE_UPDATE_PROFILE = 2563;

    private UserModel userModel;

    public ProfileFragment() {}

    public static ProfileFragment newInstance() {
        return new ProfileFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        ButterKnife.bind(this, view);
        initViews();
        getCustomerProfile();
        return view;
    }

    @OnClick({R.id.myAddressesLayout, R.id.updatePasswordLayout,
            R.id.updateProfileLayout, R.id.logoutLayout})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.myAddressesLayout:
                startActivity(new Intent(BaseActivity.currentActivity, MyAddressesActivity.class));
                break;
            case R.id.updateProfileLayout:
                Intent updateProfileIntent = new Intent(BaseActivity.currentActivity, UpdateProfileActivity.class);
                updateProfileIntent.putExtra("userModel", userModel);
                startActivityForResult(updateProfileIntent, REQUEST_CODE_UPDATE_PROFILE);
                break;
            case R.id.updatePasswordLayout:
                startActivity(new Intent(BaseActivity.currentActivity, UpdatePasswordActivity.class));
                break;
            case R.id.logoutLayout:
                DialogHelper.showTwoButtonsDialog(BaseActivity.currentActivity, logoutAlertText,
                        new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                logOutOnWeb();
                            }
                        }, new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        });
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE_UPDATE_PROFILE &&
                resultCode == RESULT_OK){
            userModel = SessionHelper.getUser();
            firstnamePizzalinkInfoLayout.setText(userModel.getFirstname());
            lastnamePizzalinkInfoLayout.setText(userModel.getLastname());
            emailPizzalinkInfoLayout.setText(userModel.getEmail());
            phonePizzalinkInfoLayout.setText(userModel.getTelephone());
        }
    }

    private void initViews(){
        setPizzalinkToolbarFields(false, fragmentTitle);
    }

    private void getCustomerProfile(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<UserModel>> call = ApiService.apiInterface.getCustomerProfile(
                SessionHelper.getCustomerToken().getToken());
        call.enqueue(new Callback<ResponseObject<UserModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<UserModel>> call, Response<ResponseObject<UserModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    setFields(response.body().getData());
                }
                else {
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private void setFields(UserModel user){

        user.checkNull();
        userModel = user;
        SessionHelper.saveCustomer(userModel);

        firstnamePizzalinkInfoLayout.setText(userModel.getFirstname());
        lastnamePizzalinkInfoLayout.setText(userModel.getLastname());
        emailPizzalinkInfoLayout.setText(userModel.getEmail());
        phonePizzalinkInfoLayout.setText(userModel.getTelephone());
    }

    private void logOutOnWeb(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject> call = ApiService.apiInterface.logout(SessionHelper.getCustomerToken().getToken());
        call.enqueue(new Callback<ResponseObject>() {
            @Override
            public void onResponse(Call<ResponseObject> call, Response<ResponseObject> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() && response.body().isSuccess())
                    logoutLocally();
                else
                    ApiErrorUtils.parseError(response);
            }

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

    private void logoutLocally(){
        SharedPrefsHelper.clearCustomerInfo();
        SharedPrefsHelper.clearCustomerToken();
        SharedPrefsHelper.setCustomerLoggedIn(false);
        BaseActivity.currentActivity.startActivity(new Intent(BaseActivity.currentActivity, LoginActivity.class));
        BaseActivity.currentActivity.finishAffinity();
    }
}
