package ch.pizzalemon.android.api;

import android.content.Intent;

import java.lang.annotation.Annotation;

import ch.pizzalemon.android.R;
import ch.pizzalemon.android.activity.BaseActivity;
import ch.pizzalemon.android.activity.LoginActivity;
import ch.pizzalemon.android.helper.DialogHelper;
import ch.pizzalemon.android.helper.SharedPrefsHelper;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Response;

public class ApiErrorUtils {

    public static void parseError(Response<?> response) {
        Converter<ResponseBody, ApiError> converter = ApiService.retrofit.responseBodyConverter(ApiError.class, new Annotation[0]);
        ApiError error = new ApiError();
        error.setStatusCode(response.code());

        BaseResponse baseResponse = (BaseResponse) response.body();

        if(baseResponse != null){

            if(baseResponse.getErrorCode() == ApiConstants.APP_ERROR_CODE_AUTHORIZATION){
                SharedPrefsHelper.clearCustomerInfo();
                SharedPrefsHelper.clearCustomerToken();
                SharedPrefsHelper.setCustomerLoggedIn(false);
                BaseActivity.currentActivity.startActivity(new Intent(BaseActivity.currentActivity, LoginActivity.class));
                BaseActivity.currentActivity.finishAffinity();
                return;
            }

            if(baseResponse.getMessage() != null && !baseResponse.getMessage().isEmpty()){
                DialogHelper.showAlertDialog(BaseActivity.currentActivity, baseResponse.getMessage());
                return;
            }
        }


        try {
            error = converter.convert(response.errorBody());
            DialogHelper.showDialogWithPositiveButton(BaseActivity.currentActivity, error.getMessage());
        } catch (Exception e) {
            DialogHelper.showDialogWithPositiveButton(BaseActivity.currentActivity, BaseActivity.currentActivity.getString(R.string.something_went_wrong));
        }
    }

    public static void parseErrorWithoutAuthorizationErrorControl(Response<?> response) {
        Converter<ResponseBody, ApiError> converter = ApiService.retrofit.responseBodyConverter(ApiError.class, new Annotation[0]);
        ApiError error = new ApiError();
        error.setStatusCode(response.code());

        BaseResponse baseResponse = (BaseResponse) response.body();

        if (baseResponse != null && baseResponse.getMessage() != null && !baseResponse.getMessage().isEmpty()) {
            DialogHelper.showAlertDialog(BaseActivity.currentActivity, baseResponse.getMessage());
            return;
        }

        try {
            error = converter.convert(response.errorBody());
            DialogHelper.showDialogWithPositiveButton(BaseActivity.currentActivity, error.getMessage());
        } catch (Exception e) {
            DialogHelper.showDialogWithPositiveButton(BaseActivity.currentActivity, BaseActivity.currentActivity.getString(R.string.something_went_wrong));
        }
    }

}
