package controllers;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import model.SceneCode;
import model.Session;
import model.User;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * Created by samschofield on 15/03/17.
 */
public class MainController extends Controller{

    @FXML
    TextField username;
    @FXML
    PasswordField password;
    @FXML
    private ComboBox<String> accountType;

    public void register() throws Exception{
        changeScene(SceneCode.REGISTER);
    }

    public boolean validateLogin(String user, String pass){
        if (Session.session.getDataManager().getUsers().get(user).checkPassword(pass) && User.AccountType.getValueOf(accountType.getValue()) == User.AccountType.PASSENGER){
            return true;
        }
        if (Session.session.getDataManager().getDrivers().get(user).checkPassword(pass) && User.AccountType.getValueOf(accountType.getValue()) == User.AccountType.DRIVER){
            return true;
        }
        return false;
    }

    public void login() throws Exception {
        //validate login
        if (validateLogin(username.getText(), password.getText())){
            parent.getSession().setUserCode(username.getText());
            changeScene(SceneCode.HOME);
        }else{
            popUp(Alert.AlertType.WARNING, "Warning!", "Invalid Login!", "Your password and username do not match a record in our database.");
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        ObservableList<String> accountTypes = FXCollections.observableArrayList();
        accountTypes.addAll(User.AccountType.DRIVER.name, User.AccountType.PASSENGER.name);
        accountType.setItems(accountTypes);
        accountType.getSelectionModel().select(0);
    }
}
