package vut.msa.helpers;

import org.apache.log4j.Logger;
import vut.msa.pojos.ClientInformation;

/**
 * Helper pre objekt ClientInfo. Trieda poskytuje zakladne funkcie pre pracu s objektom
 * ClientInfo (informacie z klienta), ako su vytvorenie, zmazanie, ziskanie a podobne.
 *
 */
public class ClientInfoHelper extends Helper {

    private ClientInformation info;
    private static final Logger llog = Logger.getLogger(UsersHelper.class);

    public ClientInfoHelper () {
        super();
        //info = new ClientInformation();
    }

    /**
     * Funkcia nacita informacie o klientovi (podla jeho ID) z databazy.
     *
     * @param clientID ID klienta, ktoreho informacie chceme nacitat
     * @return informacie o klientovi
     */
    public ClientInformation getInformationForClient (int clientID) {

        this.info = null;

        try {
            openSession();
            info = (ClientInformation) session.get(ClientInformation.class, new Integer(clientID).shortValue());

            if (info != null)
                session.load(ClientInformation.class, info.getId());
        } catch (Exception ex) {
            endTransaction(session.getTransaction(), false);
            llog.error("Nie je mozne ziskat uzivatela zo zadanym ID:" + clientID, ex);
        }

        return info;
    }

    /**
     * Funkcia ulozi nove informacie do databazy.
     *
     * @param newInfo informacie o klientovi
     * @return true, ak sa ulozenie podarilo, false, ak nie.
     */
    public boolean enterNewInformation(ClientInformation newInfo) {

        try {
            openSession();

            llog.info("Saving new information for client: " + newInfo.getClient().getClientName());

            //Jedna sa o transietny objekt, preto treba volat persist
            session.persist(newInfo);
            endTransaction(session.getTransaction(), true);
            return true;

        } catch (Exception lex) {
            llog.error(lex.getMessage());
            return false;
        }
    }

    /**
     * Funkcia aktualizuje informacie v databaze o klientovi.
     *
     * @param info nove informacie, ktore sa ulozia do databazy
     * @return true, ak sa ulozenie podarilo, false, ak nie.
     */
    public synchronized boolean updateInformation(ClientInformation info) {

        try {

            openSession();
            llog.info("Aktualizujem informacie pre klienta: " + info.getClient().getClientName());
            session.merge(info);
            endTransaction(session.getTransaction(), true);
            return true;

        } catch (Exception lex) {
            llog.error(lex.getMessage());
            return false;
        }
    }



}
