package com.example.todocloud.datasynchronizer;

import android.util.Log;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.todocloud.app.AppConfig;
import com.example.todocloud.app.AppController;
import com.example.todocloud.data.User;
import com.example.todocloud.datastorage.DbConstants;
import com.example.todocloud.datastorage.DbLoader;
import com.example.todocloud.helper.InstallationIdHelper;
import com.example.todocloud.helper.OnlineIdGenerator;
import com.example.todocloud.helper.SessionManager;

import org.json.JSONException;
import org.json.JSONObject;

public class UserDataSynchronizer extends DataSynchronizer {

  private static final String TAG = UserDataSynchronizer.class.getSimpleName();

  private OnRegisterUserListener onRegisterUserListener;
  private OnLoginUserListener onLoginUserListener;
  private DbLoader dbLoader;

  public UserDataSynchronizer(DbLoader dbLoader) {
    this.dbLoader = dbLoader;
  }

  public void setOnRegisterUserListener(OnRegisterUserListener onRegisterUserListener) {
    this.onRegisterUserListener = onRegisterUserListener;
  }

  public void setOnLoginUserListener(OnLoginUserListener onLoginUserListener) {
    this.onLoginUserListener = onLoginUserListener;
  }

  public void registerUser(
      final String user_online_id,
      final String name,
      final String email,
      final String password,
      final long _id
  ) {
    String tag_json_object_request = "request_register";

    JSONObject jsonRequest = new JSONObject();
    try {
      putUserRegisterData(user_online_id, name, email, password, jsonRequest);
    } catch (JSONException e) {
      e.printStackTrace();
      String errorMessage = "Unknown error";
      onRegisterUserListener.onSyncError(errorMessage);
    }

    JsonObjectRequest registerRequest = new JsonObjectRequest(
        JsonObjectRequest.Method.POST,
        AppConfig.URL_REGISTER,
        jsonRequest,
        new Response.Listener<JSONObject>() {

          @Override
          public void onResponse(JSONObject response) {
            Log.d(TAG, "Register Response: " + response);
            try {
              boolean error = response.getBoolean("error");

              if (!error) {
                onRegisterUserListener.onFinishRegisterUser();
              } else {
                String message = response.getString("message");
                if (message == null) message = "Unknown error";
                if (message.contains("Oops! An error occurred while registereing")) {
                  handleError();
                } else {
                  onRegisterUserListener.onSyncError(message);
                }
              }
            } catch (JSONException e) {
              e.printStackTrace();
              String errorMessage = "Unknown error";
              onRegisterUserListener.onSyncError(errorMessage);
            }
          }

          /**
           * Generally the cause of error is, that the userOnlineId generated by the client is
           * already registered in the remote database. In this case, it generate a different
           * userOnlineId, and send the registration request again.
           */
          private void handleError() {
            InstallationIdHelper.getNewInstallationId();
            String new_user_online_id = OnlineIdGenerator.generateOnlineId(
                DbConstants.User.DATABASE_TABLE,
                _id
            );
            registerUser(new_user_online_id, name, email, password, _id);
          }

        },
        new Response.ErrorListener() {

          @Override
          public void onErrorResponse(VolleyError error) {
            String errorMessage = error.getMessage();
            Log.e(TAG, "Register Error: " + errorMessage);
            if (errorMessage == null) errorMessage = "Unknown error";
            onRegisterUserListener.onSyncError(errorMessage);
          }

        }
    );

    AppController.getInstance().addToRequestQueue(registerRequest, tag_json_object_request);
  }

  public void loginUser(String email, String password) {
    String tag_json_object_request = "request_login";

    JSONObject jsonRequest = new JSONObject();
    try {
      putUserLoginData(email, password, jsonRequest);
    } catch (JSONException e) {
      e.printStackTrace();
      String errorMessage = "Unknown error";
      onLoginUserListener.onSyncError(errorMessage);
    }

    JsonObjectRequest loginRequest = new JsonObjectRequest(
        JsonObjectRequest.Method.POST,
        AppConfig.URL_LOGIN,
        jsonRequest,
        new Response.Listener<JSONObject>() {

          @Override
          public void onResponse(JSONObject response) {
            Log.d(TAG, "Login Response: " + response);
            try {
              boolean error = response.getBoolean("error");

              if (!error) {
                handleLogin(response);
                onLoginUserListener.onFinishLoginUser();
              } else {
                String message = response.getString("message");
                if (message == null) message = "Unknown error";
                onLoginUserListener.onSyncError(message);
              }
            } catch (JSONException e) {
              e.printStackTrace();
              String errorMessage = "Unknown error";
              onLoginUserListener.onSyncError(errorMessage);
            }
          }

          private void handleLogin(JSONObject response) throws JSONException {
            User user = new User(response);
            dbLoader.createUser(user);
            SessionManager sessionManager = SessionManager.getInstance();
            sessionManager.setLogin(true);
          }

        },
        new Response.ErrorListener() {

          @Override
          public void onErrorResponse(VolleyError error) {
            String errorMessage = error.getMessage();
            Log.e(TAG, "Login Error: " + errorMessage);
            if (errorMessage == null) errorMessage = "Unknown error";
            onLoginUserListener.onSyncError(errorMessage);
          }

        }
    );

    AppController.getInstance().addToRequestQueue(loginRequest, tag_json_object_request);
  }

  private void putUserRegisterData(
      String user_online_id,
      String name,
      String email,
      String password,
      JSONObject jsonRequest
  ) throws JSONException {
    jsonRequest.put("user_online_id", user_online_id);
    jsonRequest.put("name", name);
    jsonRequest.put("email", email);
    jsonRequest.put("password", password);
  }

  private void putUserLoginData(
      String email,
      String password,
      JSONObject jsonRequest
  ) throws JSONException {
    jsonRequest.put("email", email);
    jsonRequest.put("password", password);
  }

  public interface OnRegisterUserListener {
    void onFinishRegisterUser();
    void onSyncError(String errorMessage);
  }

  public interface OnLoginUserListener {
    void onFinishLoginUser();
    void onSyncError(String errorMessage);
  }

}

@@ -697,33 +697,8 @@
 zer 
-extends DataSynchronizer 
 %7B%0A%0A 

Remove unused inheritance