/*
 * Copyright 2009 Lari Natri <lari.natri@gmail.com>
 *
 *  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/>.
 */


package compid.importers;

import net.aavalla.utils.jobpool.Job;
import net.aavalla.utils.jobpool.JobCategory;
import net.aavalla.utils.jobpool.ParameterizedJob;
import compid.application.CompidApp;
import compid.data.DAOFactory;
import compid.data.FullDataset;
import compid.data.UpdateHandler;



/**
 *
 * @author Lari Natri
 */
public abstract class DatasetFileImporter<P extends DatasetFileImporterParams> extends ParameterizedJob<Object,P> {

    private class DatasetParser extends Job<FullDataset,P> {

        private DatasetParser(P p) {
            super(p);
            this.setName("Dataset parser");
            this.addCategory(JobCategory.MEMORY);
        }

        @Override
        protected FullDataset work(P params) throws Throwable {
            return DatasetFileImporter.this.getAsDataSet(params);
        }

    }

    private class DatasetInjecter extends Job<Object,FullDataset> {
        private DatasetInjecter(FullDataset dataset) {
            super(dataset);
            this.setName("Dataset injecter");
            this.addCategory(JobCategory.DB_WRITE);
            this.addConflictingCategory(JobCategory.DB_READ);
            this.addConflictingCategory(JobCategory.DB_WRITE);
        }

        @Override
        protected Object work(FullDataset p) throws Throwable {
            UpdateHandler uh = DAOFactory.getInstance().getUpdateHandler();
            uh.addFullDataset(p);
            CompidApp.getApplication().getDatasetsHandler().refresh();
            return null;
        }

    }

    public DatasetFileImporter() {
        super();
        this.setName("Dataset importer");
    }

    @Override
    protected Object work(final P p) throws Throwable {
        //this.reportProgress(1);
        FullDataset dataset = waitSubJob(new DatasetParser(p));
        //this.reportProgress(60);
        return waitSubJob(new DatasetInjecter(dataset));
        

    }

    public abstract String getFileNameExtension();
    protected abstract FullDataset getAsDataSet(P p)
            throws ImportException;



}
