/*
 * #%L
 * IsisFish data
 * %%
 * Copyright (C) 2009 - 2014 Ifremer, Code Lutin, Jean Couteau
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
package sensitivityexports;

import java.io.File;
import java.io.Writer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.math.matrix.MatrixND;

import org.nuiton.util.ReverseFileReader;
import fr.ifremer.isisfish.datastore.ResultStorage;
import fr.ifremer.isisfish.datastore.SimulationStorage;
import fr.ifremer.isisfish.entities.Population;
import fr.ifremer.isisfish.export.SensitivityExport;
import fr.ifremer.isisfish.types.TimeStep;
import fr.ifremer.isisfish.annotations.Doc;
import resultinfos.MatrixCatchWeightPerStrategyMetPerZonePop;

public class SensitivityCatchWeightReferenceY7 implements SensitivityExport {

    /** to use log facility, just put in your code: log.info("..."); */
    static private Log log = LogFactory
            .getLog(SensitivityCatchWeightReferenceY7.class);

    protected String[] necessaryResult = {
        MatrixCatchWeightPerStrategyMetPerZonePop.NAME
    };

    @Doc("Population")
    public Population param_pop;

    @Doc("Path of the CapturesPoids.csv file")
    public String param_referenceCatchWeightCSV ="";

    @Override
    public void export(SimulationStorage simulation, Writer out)
            throws Exception {
        ResultStorage resultStorage = simulation.getResultStorage();
        TimeStep lastStep = resultStorage.getLastStep();
        Double capturesWeight = 0.0;
        Double capturesWeightReference = 0.0;

        File referenceFile = new File(param_referenceCatchWeightCSV);

        //instantiate a reader that starts reading from the file end.
        ReverseFileReader reader = new ReverseFileReader(referenceFile);

        //read the last line of the file (should be empty)
        String line = reader.readLine();

        //read the next line (the last written line)
        line = reader.readLine();

        Integer lastMonth = 0;

        while (line != null ) {

            String[] items = line.split(";");

            //If we did not initiate the last date (we are on the last line of
            // the file), we do it now with the value of the date.
            if (lastMonth == 0) {
                lastMonth = Integer.parseInt(items[4]);
            }

            Integer month = Integer.parseInt(items[4]);

            if ((items[0].equals(param_pop.getName())) && (month>lastMonth-12)){
                capturesWeightReference += Double.parseDouble(items[5]);
            }
            line = reader.readLine();
        }

        for (Population pop : simulation.getParameter().getPopulations()) {
            if (pop.getName().equals(param_pop.getName())) {
                for (int i = 0; i < 12; i++) {

                    //Get the captures Weight of each month of the last year
                    MatrixND matlastdate = resultStorage.getMatrix(
                                    new TimeStep(lastStep.getStep() - i),
                                    pop,
                                    MatrixCatchWeightPerStrategyMetPerZonePop.NAME);
                    capturesWeight += matlastdate.sumAll();
                }
            }
        }

        log.info("capturesWeight value : " + capturesWeight);
        log.info("capturesWeightReference value : " + capturesWeightReference);

        out.write(Double.toString(capturesWeight / capturesWeightReference));
    }

    @Override
    public String getDescription() {
        return "Captures in weight for the last year for the popage " +
                "population. Captures is the sum of zones, groups, metiers " +
                "and strategies";
    }

    @Override
    public String getExportFilename() {
        return "SensitivityCapturesWeightReferenceY7_" + param_pop.getName();
    }

    @Override
    public String getExtensionFilename() {
        return ".csv";
    }

    @Override
    public String[] getNecessaryResult() {
        return this.necessaryResult;
    }

}
