package server.servlets;


import java.util.Properties;

/**
 * LoginProcess Class
 * @author Dawn Hallaman
 */

public class LoginProcess {

// This is where the Properties File gets initialized
    static final String FORMC_PROPERTY_FILE = Globals.FORMC_PROPERTY_FILE;

//  This was the database reader I replaced with SQLBeanie. SQLBeanie has more methods for database access.
//  private DatabaseReader dbr = new DatabaseReader();

    private SQLBeanie dbr = new SQLBeanie();
    private LoginHtml lh = new LoginHtml();
    private String formActionURL;
    private String loginRedirectURL;

    private final String errorMsg[] =
            {"Error: Invalid User or Password. Try Again",
             "Error: Unknown"
            };

    private final int ERROR_INVALID_USER = 0;
    private final int ERROR_UNKNOWN = 1;

    /**
     * LoginProcess  Constructor
     */

    public LoginProcess() {
        try {
            Properties prop = server.servlets.FileUtil.loadProperties(FORMC_PROPERTY_FILE);
            formActionURL = prop.getProperty("LoginURL");
            //  formActionURL ="http://localhost:8080/examples/servlet/Login";

            System.out.println(" The formActionURL from method LoginProcess is " + formActionURL);
            loginRedirectURL = prop.getProperty("FormCURL");

            //  loginRedirectURL = "http://localhost:8080/examples/servlet/FormC";
            System.out.println(" The formActionURL from method LoginProcess is " + loginRedirectURL);
            System.out.println("is the dbr open?");
            //  dbr.open();
        } catch (PropFileException pfnf) {
            pfnf.printStackTrace();
        }
    }

    /**
     * Checks UserId and Password entered is a valid one.
     *
     * @parm     String         user
     * @parm     String      password
     * @return   boolean
     */

    public boolean isValid(String user, String password) {
        System.out.println("Trying to validate user");

        if (dbr.checkRecordExists(LoginSQL.getLoginScript(user, password))) {
            return true;
        } else {
            System.out.println("Invalid user");
            return false;
        }

    }

    /**
     * Returns the Login Page URL
     *
     * @return          String          URL
     */

    public String getLoginRedirectURL() {
        return loginRedirectURL;
    }

    /**
     * getLoginPage  Method
     *
     * Returns the Login Page
     *
     * @return      String          html
     */

    public String getLoginPage() {
        System.out.println(
                " The formActionURL from method getLoginPage is " + formActionURL);
        lh.setNextActionURL(formActionURL);
        return lh.getLoginPage();
    }

    /**
     * Returns the Error Login Page
     *
     * @return           String     html
     */

    public String getLoginErrorPage() {
        lh.setNextActionURL(formActionURL);
        return lh.getLoginErrorPage(errorMsg[ERROR_INVALID_USER]);
    }

}