package hirondelle.movies.login;
import hirondelle.movies.main.MainWindow;
import java.util.logging.Logger;
import hirondelle.movies.util.Util;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public final class LoginController implements ActionListener {
@Override public void actionPerformed(ActionEvent aEvent) {
String command = aEvent.getActionCommand();
if ( LOGIN.equals(command) ) {
validateUserCredentials();
}
else if( CANCEL.equals(command) ){
shutDownApplication();
}
else {
throw new AssertionError("Unexpected command: " + command);
}
}
public void askUserForCredentials(){
fView = new LoginView(this);
fView.showLoginScreen();
}
void validateUserCredentials(){
fNumAttempts++;
String userName = fView.getUserName();
String password = fView.getPassword();
if (isValid(userName, password)){
fView.close();
showMainWindow(userName);
}
else {
if(fNumAttempts < MAX_NUM_ATTEMPTS) {
fView.tryAgain();
}
else {
fLogger.config("Shutting down. User credentials not valid for more than the max number of tries.");
shutDownApplication();
}
}
}
static final String LOGIN = "Login";
static final String CANCEL = "Cancel";
private LoginView fView;
private int fNumAttempts = 0;
private static final int MAX_NUM_ATTEMPTS = 3;
private static final Logger fLogger = Util.getLogger(LoginController.class);
private boolean isValid(String aUserName, String aPassword){
return Util.textHasContent(aUserName) && ! "failme".equals(aUserName);
}
private void showMainWindow(String aUserName){
fLogger.config("Showing the main window.");
MainWindow.getInstance().buildAndShow(aUserName);
}
private void shutDownApplication() {
fView.close();
System.exit(0);
}
}