package no.noen.server.term;

import no.noen.lms.Terminal;
import no.noen.lms.TerminalType;
import org.komsa.log.LogWriter;
import org.komsa.server.entity.EntityFactory;

/**
 * Terminal factory.
 */
public class TerminalFactory {
    /** Hidden constructor. */
    protected TerminalFactory() {
    }

    /**
     * Create terminal connection.
     * @param terminal Terminal metadata
     * @return ITerminal object.
     */
    public static ITerminal createTerminalConnection(Terminal terminal) throws Exception {
        TerminalFactory fac = new TerminalFactory();
        return fac.getConn(terminal);
    }

    /**
     * @param terminal Terminal data
     * @return an instance of ITerminal.
     */
    protected ITerminal getConn(Terminal terminal) throws Exception {
        ITerminal termConn = null;
        try {
            String strTypeId = terminal.get(Terminal.F_TYPEID);
            EntityFactory efac = new EntityFactory();
            TerminalType terminalType = 
                (TerminalType)efac.getEntity("lms", "TerminalType", strTypeId);
            if (terminalType == null)
                new Exception("Invalid terminal type " + strTypeId);
            String clsName = terminalType.getITerminalClass();
            termConn = (ITerminal)Class.forName(clsName, true, 
                this.getClass().getClassLoader()).newInstance();
            if (termConn != null)
                termConn.init(terminal.getIPAddr(), terminalType);
        } catch (Exception ex) {
            LogWriter.elog(ex, "TerminalFactory.getConn: " + terminal.getName());
            throw ex;
        }
        return termConn;
    }

}
