/*
 * This file is part of DebGen Biobank Software developed by ASTRID Research.
 * All rights reserved. Reproduction, modification, use or disclosure
 * to third parties without express authority is forbidden.
 *
 * Copyright ASTRID Research Inc., Hungary, 2009-2010.
 *
 * ASTRID Research
 * Headquaters: Csapo utca 42. Debrecen H-4029 HUNGARY
 * Phone: +36-52-533-173        Fax: +36-52-533-174
 * Web: http://www.astrid.hu    E-mail: info@astrid.hu
 *
 * Project name: DebGen Biobank Software project.
 * URLS:
 * Developers: Istvan Zoltan Nagy (istvan.nagy@astrid.hu)
 */
package hu.astrid.debgen.patientmanagement.service.modules;

import hu.astrid.debgen.exception.DebGenException;
import hu.astrid.debgen.patientmanagement.domain.modules.Result;
import hu.astrid.debgen.patientmanagement.domain.modules.requests.AnalysisRequest;
import hu.astrid.debgen.patientmanagement.domain.modules.requests.LabelList;
import hu.astrid.debgen.server.startup.ApplicationParameters;
import hu.astrid.printxml.exception.PatientPrintException;
import hu.astrid.printxml.generator.PdfGeneratorFromURI;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 *
 * @author inagy
 */
public class PrintManagerService {

    /**
     * Returns an instance of a PatientManagerService and sets its session.
     * @return A new instance.
     */
    public static PrintManagerService getInstance() {
        return new PrintManagerService();
    }
    private static Logger logger = Logger.getLogger(PrintManagerService.class);

    public List<URI> generatePdfFromAnalysis(AnalysisRequest analysis, Locale locale) throws IOException, PatientPrintException, Exception {
        File xml = createTempXML();
        FileOutputStream fos = new FileOutputStream(xml);
        analysis.convertToXml(new URL(ApplicationParameters.getApplicationURL() + "/patient.xsd"), fos);
        PdfGeneratorFromURI generator = new PdfGeneratorFromURI(locale);
        if (analysis.getObjectType().equals("born")) {
            generator.setResourceName("/hu/astrid/debgen/print/templates/BornDefectAnalysisRequest-");
        } else if (analysis.getObjectType().equals("onkohaem")) {
            generator.setResourceName("/hu/astrid/debgen/print/templates/OncohaematologyAnalysisRequest-");
        } else if (analysis.getObjectType().equals("const")) {
            generator.setResourceName("/hu/astrid/debgen/print/templates/ConstitutionalAnalysisRequest-");
        } else {
            throw new Exception("none");
        }
        URI xmlUri = xml.toURI();
        ArrayList<URI> list = new ArrayList<URI>(2);
        list.add(xmlUri);
        list.add(generator.getAsURI(xmlUri));
        return list;
    }

    public URI generatePdfFromModule(Result module, Locale locale) throws IOException, PatientPrintException, Exception {
        logger.info("generating pdf from module ["+module+"] with locale ["+ locale +"]");
        File xml = createTempXML();
        FileOutputStream fos = new FileOutputStream(xml);
        if (module.getRequest() != null) {
            module.getRequest().setLabels(new LabelList());
        }
        module.convertToXml(new URL(ApplicationParameters.getApplicationURL() + "/patient.xsd"), fos);
        PdfGeneratorFromURI generator = new PdfGeneratorFromURI(locale);
        if (module.getObjectType().equals("citogen")) {
            generator.setResourceName("/hu/astrid/debgen/print/templates/CitogenModule-");
        } else if (module.getObjectType().equals("fish")) {
            generator.setResourceName("/hu/astrid/debgen/print/templates/FishModule-");
        } else if (module.getObjectType().equals("hypo")) {
            generator.setResourceName("/hu/astrid/debgen/print/templates/HypoModule-");
        } else if (module.getObjectType().equals("acho")) {
            generator.setResourceName("/hu/astrid/debgen/print/templates/AchoModule-");
        } else if (module.getObjectType().equals("fmr1")) {
            generator.setResourceName("/hu/astrid/debgen/print/templates/FMR1Module-");
        } else {
            logger.error("Unknown module type found: " + module.getObjectType());
            throw new Exception("Unknown module type found: " + module.getObjectType());
        }
        URI xmlUri = xml.toURI();
        //ArrayList<URI> list = new ArrayList<URI>(2);
        //list.add(xmlUri);
        //list.add(generator.getAsURI(xmlUri));
        URI pdfUri = null;
        try {
            pdfUri = generator.getAsURI(xmlUri);
        } catch (PatientPrintException patientPrintException) {
            logger.error(patientPrintException.getRootCause().getMessage(), patientPrintException.getRootCause());
        }
        boolean deleted = xml.delete();
        if (!deleted) {
            logger.error("Can't delete file: " + xml.getAbsolutePath());
        }
        return pdfUri;
        //return list;
    }

    private File createTempXML() throws DebGenException {
        try {
            String tempDir = System.getenv("TMP");
            //Query TEMP directory of the user or operating system
            if (tempDir == null || tempDir.isEmpty()) {
                tempDir = System.getenv("TEMP");
            }
            if (tempDir == null || tempDir.isEmpty()) {
                tempDir = System.getProperty("java.io.tmpdir");
            }
            if (tempDir == null || tempDir.isEmpty()) {
                throw new DebGenException("No temp directory set in the used operating system!");
            }
            File tempFile = File.createTempFile("report-" + new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SS").format(new Date()) + "-", ".xml", new File(tempDir));
            tempFile.deleteOnExit();
            return tempFile;
        } catch (IOException ex) {
            throw new DebGenException("Can't create temp file.", ex);
        }
    }
}
