package dendrarium.core.beans;

import dendrarium.portal.admin.Upload;
import dendrarium.utils.ELHelper;
import dendrarium.utils.StreamUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Serializable;
import org.hibernate.Session;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;

/**
 * Wykonuje zadania porzadkujace przy starcie aplikacji.
 *
 * @author Piotr Achinger <piotr.achinger at gmail.com>
 */
@org.jboss.seam.annotations.Startup
@Name("startup")
@Scope(ScopeType.APPLICATION)
public class Startup implements Serializable {

    @Logger
    Log log;

    @In(create = true)
    Session session;

    @In(create = true)
    Upload upload;

    @Create
    public void napraw() {
        session.beginTransaction();

        String ios = ELHelper.property("import_on_startup");
        if (ios.equals("true")) {
            dodajPrzykladoweTaski();
        }

        session.flush();
        session.getTransaction().commit();
    }

    private void dodajPrzykladoweTaski() {
        String strName = "/dendrarium/resources/resources.list";

        if (!session.createQuery("from TaskBusinessProcess").setMaxResults(1).list().isEmpty()) {
            log.info("STARTUP: sa juz taski, wiec nie wrzucam resources.list");
            return;
        }

        try {
            BufferedReader objBin = new BufferedReader(new InputStreamReader(
                    this.getClass().getResourceAsStream(strName)));

            if (objBin != null) {
                String strLine = null;
                while ((strLine = objBin.readLine()) != null) {
                    strLine = strLine.trim();
                    if (strLine.startsWith("#") || strLine.equals("")) {
                        /* komentarz */
                        continue;
                    }

                    log.info("UPLOADING RESOURCE: " + strLine);

                    byte[] data = StreamUtils.obtainByteData("/dendrarium/resources/" + strLine);
                    upload.setData(data);
                    upload.upload();

                }
                objBin.close();
            } else {
                log.info(">>> Error: Unable to retrieve InputStream");
            }
        } catch (Exception e) {
            log.error(">>> ", e);
        }

    }
}
