/*
 * The Broad Institute
 * SOFTWARE COPYRIGHT NOTICE AGREEMENT
 * This is copyright (2007-2008) by the Broad Institute/Massachusetts Institute 
 * of Technology.  It is licensed to You under the Gnu Public License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *    http://www.opensource.org/licenses/gpl-2.0.php
 *
 * This software is supplied without any warranty or guaranteed support
 * whatsoever. Neither the Broad Institute nor MIT can be responsible for its
 * use, misuse, or functionality.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.broad.igv.preprocess;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Map;
import org.broad.igv.data.Dataset;
import org.broad.igv.data.IGVDataset;
import org.broad.igv.data.ResourceLocator;
import org.broad.igv.data.WiggleParser;
import org.broad.igv.track.TrackType;

/**
 *
 * @author Mitchell Guttman, Jim Robinson
 */
public class IGVPreprocessor {

    static String usageString = "preprocess.sh inputFileOrDirectory  outputFileOrDirectory genome [-w windowSize] [-name trackName] [-type type]";

    /**
     * Required parameters
     *      -i [input directory]
     *      -o [output directory]
     *      -genome [genome]
     * @param args
     */
    public static void main(String[] args) {


        if (args.length < 3) {
            System.out.println("Usage: " + usageString);
            System.exit(-1);
        }

        String inputDirectoryPath = args[0];
        String outputFN = args[1];
        String genomeId = args[2];


        Map<String, String> argMap = ProcessingUtils.parseArgs(args, 3);

        File inputFileOrDir = new File(inputDirectoryPath);
        File outputFile = new File(outputFN);

        int span = 25;
        String spanString = argMap.get("-w");
        try {
            span = Integer.parseInt(spanString);

        } catch (NumberFormatException e) {
        }

        String name = argMap.get("-name");
        if (name == null) {
            name = outputFile.getName();
        }





        int maxZoom = 6;
        String maxZoomLevel = argMap.get("-z");
        if (maxZoomLevel != null && maxZoomLevel.length() > 0) {
            try {
                maxZoom = Integer.parseInt(maxZoomLevel);
            } catch (NumberFormatException numberFormatException) {
                System.err.println(numberFormatException.getMessage());
            }
        }

        if (!inputFileOrDir.exists()) {
            System.out.println("Cannot read input directory: " + inputFileOrDir.getAbsolutePath() +
                    " Exiting.");
            System.exit(-1);
        }
        if (outputFile.isDirectory()) {
            System.out.println("Output file is a directory (" + outputFN +
                    ".  Filename is required.  Exiting");
            System.exit(-1);
        }

        String shortFileName = inputFileOrDir.getName().toLowerCase();
        if (shortFileName.endsWith(".txt") || shortFileName.endsWith(".tab") || shortFileName.endsWith(
                ".xls")) {
            shortFileName = shortFileName.substring(0, shortFileName.lastIndexOf("."));
        }

        if (!inputFileOrDir.isDirectory() && (shortFileName.endsWith(".cn") || shortFileName.endsWith(
                ".xcn") || shortFileName.endsWith(".snp"))) {
            processCN(inputFileOrDir, outputFile, genomeId, name, TrackType.COPY_NUMBER);
        } else if (inputFileOrDir.isDirectory()) {
            processCNBin(inputFileOrDir, outputFile, genomeId, name, TrackType.OTHER, span, null);
        } else {
            processWig(inputFileOrDir, outputFile, genomeId, name);
        }
    }

    private static void processCN(File inputFile, File outputFile, String genomeId, String name,
            TrackType type) {

        IGVDataset ds = new IGVDataset(genomeId, inputFile);
        ds.setName(name);
        ds.setTrackType(type);
        (new NonOverlappingProcessor(ds, null)).process(outputFile.getAbsolutePath());
    }

    private static void processCNBin(File inputDir, File outputFile, String genomeId, String name,
            TrackType type, int wSpan, final String filterString) {


        FilenameFilter filter = new FilenameFilter() {

            public boolean accept(File dir, String name) {
                return name.endsWith(".bin") && (!name.contains("_random") && ((filterString == null) || name.contains(
                        filterString)));
            }
        };

        SolexaBinaryDataset ds = new SolexaBinaryDataset(name, type, genomeId,
                inputDir.getAbsolutePath(), filter);
        ds.setWindowSpan(wSpan);
        ds.setNormalized(false);

        for (String nm : ds.getDataHeadings()) {
            System.out.println(nm);
        }

        (new NonOverlappingProcessor(ds)).process(outputFile.getAbsolutePath());
    }

    private static void processWig(File inputFile, File outputFile, String genomeId, String name) {


        Dataset ds = (new WiggleParser(new ResourceLocator(inputFile.getAbsolutePath()),
                genomeId)).parse();
        ds.setName(name);

        for (String nm : ds.getDataHeadings()) {
            System.out.println(nm);
        }

        (new NonOverlappingProcessor(ds)).process(outputFile.getAbsolutePath());
    }
}
