package com.cloudycrew.cloudycar.signup;

import com.cloudycrew.cloudycar.ViewController;
import com.cloudycrew.cloudycar.controllers.UserController;
import com.cloudycrew.cloudycar.models.User;
import com.cloudycrew.cloudycar.scheduling.ISchedulerProvider;
import com.cloudycrew.cloudycar.utils.ObservableUtils;

/**
 * Created by George on 2016-11-09.
 */

public class SignUpController extends ViewController<ISignUpView> {
    private UserController userController;
    private ISchedulerProvider schedulerProvider;

    public SignUpController(UserController userController, ISchedulerProvider schedulerProvider) {
        this.userController = userController;
        this.schedulerProvider = schedulerProvider;
    }

    public void registerUser(User user) {
        ObservableUtils.fromAction(userController::createUser, user)
                       .subscribeOn(schedulerProvider.ioScheduler())
                       .observeOn(schedulerProvider.mainThreadScheduler())
                       .subscribe(nothing -> dispatchOnSuccessfulRegistration(),
                                  throwable -> dispatchOnDuplicateUsernameFailure());
    }

    private void dispatchOnDuplicateUsernameFailure() {
        if (isViewAttached()) {
            getView().onDuplicateUsernameFailure();
        }
    }

    private void dispatchOnSuccessfulRegistration() {
        if (isViewAttached()) {
            getView().onSuccessfulRegistration();
        }
    }
}

@@ -135,32 +135,129 @@
 UserController;%0A
+import com.cloudycrew.cloudycar.email.Email;%0Aimport com.cloudycrew.cloudycar.models.PhoneNumber;%0A
 import com.cloud
@@ -831,16 +831,312 @@
 ic void 
+registerUser(String username, String email, String phoneNumber) %7B%0A        try %7B%0A            User newUser = createUser(username, email, phoneNumber);%0A            registerUser(newUser);%0A        %7D catch (Exception e) %7B%0A            dispatchOnMalformedUserFailure();%0A        %7D%0A    %7D%0A%0A    private void 
 register
@@ -1532,16 +1532,423 @@
 lure());
+%0A%0A    %7D%0A%0A    private User createUser(String username, String email, String phoneNumber) %7B%0A        User newUser = new User(username);%0A        newUser.setEmail(new Email(email));%0A        newUser.setPhoneNumber(new PhoneNumber(email));%0A%0A        return newUser;%0A    %7D%0A%0A%0A    private void dispatchOnMalformedUserFailure() %7B%0A        if (isViewAttached()) %7B%0A            getView().onMalformedUserFailure();%0A        %7D
 %0A    %7D%0A%0A

Handle attempting to create a user with a bad email or phone number