package uk.ac.ebi.spot.goci.curation.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import uk.ac.ebi.spot.goci.curation.service.FtpFileService;
import uk.ac.ebi.spot.goci.repository.CatalogExportRepository;
import uk.ac.ebi.spot.goci.service.SpreadsheetProcessor;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by emma on 17/03/15.
 *
 * @author emma
 *         <p>
 *         Scheduled component that runs daily and exports a file containing details of catalog studies and drops on
 *         NCBI ftp fpr mapping
 */
@Component
public class DailyNcbiExportTask {

    private CatalogExportRepository catalogExportRepository;

    private SpreadsheetProcessor spreadsheetProcessor;

    private FtpFileService ftpFileService;

    @Autowired
    public DailyNcbiExportTask(CatalogExportRepository catalogExportRepository,
                               SpreadsheetProcessor spreadsheetProcessor,
                               FtpFileService ftpFileService) {
        this.catalogExportRepository = catalogExportRepository;
        this.spreadsheetProcessor = spreadsheetProcessor;
        this.ftpFileService = ftpFileService;
    }

    private final Logger log = LoggerFactory.getLogger(getClass());

    protected Logger getLog() {
        return log;
    }

    @Scheduled(cron = "0 0 22 * * *")
    public void dailyNcbiExport() throws IOException {

        // Create date stamped file
        String uploadDir =
                System.getProperty("java.io.tmpdir") + File.separator + "gwas_ncbi_export" + File.separator;

        DateFormat df = new SimpleDateFormat("yyyy_MM_dd");
        String dateStamp = df.format(new Date());
        File outputFile = new File(uploadDir + dateStamp + "_gwas.txt");
        outputFile.getParentFile().mkdirs();

        // If at this stage we haven't got a file create one
        if (!outputFile.exists()) {
            outputFile.createNewFile();
        }

        getLog().info("Created file: " + outputFile);

        // Call methods to create NCBI spreadsheet
        String[][] data = catalogExportRepository.getNCBISpreadsheet();
        spreadsheetProcessor.writeToFile(data, outputFile);

        // Check we have something in our output file
        if (outputFile.length() != 0) {
            getLog().info("Begin file upload to FTP...");
            ftpFileService.ftpFileUpload(outputFile);
        }
        else {
            getLog().error("File is empty");
        }
    }
}

@@ -1553,24 +1553,49 @@
 log;%0A    %7D%0A%0A
+    // Scheduled for 1am%0A
     @Schedul
@@ -1613,10 +1613,9 @@
 0 0 
-22
+0
  * *

Set time to run to midnight every day