/*******************************************************************************
 * This file is part of GECAMed.
 * 
 * GECAMed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License (L-GPL) as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GECAMed 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 Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License (L-GPL)
 * along with GECAMed.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * GECAMed is Copyrighted by the Centre de Recherche Public Henri Tudor (http://www.tudor.lu)
 * (c) CRP Henri Tudor, Luxembourg, 2008
 *******************************************************************************/
package lu.tudor.santec.gecamed.prescription.gui.drug.lists.cefip.importer;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;

import javax.swing.JProgressBar;

import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.drug.DrugList;
import lu.tudor.santec.gecamed.prescription.gui.drug.lists.cefip.CefipDrugListModule;
import lu.tudor.santec.gecamed.prescription.gui.drug.lists.cefip.DrugFileModel;

import org.apache.log4j.Logger;

import com.svcon.jdbf.DBFReader;

/**
 * 
 * This class handles all operations to import
 * the cefip drug list.
 * 
 * it can check if a given file is matching for the manufacturer and
 * drug list file recommondations. Now only the line size can be used
 * as test.
 * 
 * it can completely remove the old lists.
 * 
 * and import the new one.
 * 
 * @author martin.heinemann@tudor.lu
 *
 *
 * @version
 * <br>$Log: CefipImportWorker.java,v $
 * <br>Revision 1.7  2013-12-27 18:09:25  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.6  2013-07-15 06:18:36  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.5  2009-05-07 15:56:26  heinemann
 * <br>import of new cefip file format in ms access.
 * <br>using lib jackccess
 * <br>
 * <br>Revision 1.4  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.3  2007/03/02 08:28:39  hermen
 * <br>initial checkin after the merge of PatientModuleRebuild with the main HEAD
 * <br>
 * <br>Revision 1.2.2.2  2007/01/04 13:51:37  heinemann
 * <br>The great space cleaning lady has done a big bunch of refactoring
 * <br>
 * <br>Revision 1.2.2.1  2006/12/20 13:47:04  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.2  2006/09/13 12:01:00  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1  2006/09/11 14:40:25  heinemann
 * <br>*** empty log message ***
 * <br>
 */
public class CefipImportWorker {

	/* ------------------------------------------------------ */
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(CefipImportWorker.class.getName());
	
	private ImportCefipDrug drugImporter;
	
	private ImportATCClasses atcImporter;
	
	private ImportCefipManufacturer manufacturerImporter;
	
	private int atcCount;

	private int manuCount;

	private int drugCount;

	private ImportMdbATCClasses mdbATCImporter;

	private ImportMdbCefipManufacturer mdbManufactuerImporter;

	private ImportMdbCefipDrug mdbDrugImporter;

	
	/**
	 * Test the cefip list drug file
	 * 
	 * @param file
	 * @return
	 */
	public Integer testCefipList(File file) {
		/* ====================================================== */
		return testOldCefip(file);
		/* ====================================================== */
	}
	
	
	/**
	 * Tests for the old cefip list in dbase format
	 * 
	 * @param file
	 */
	private Integer testOldCefip(File file) {
		/* ================================================== */
		try {
			/* ---------------------------------------- */
			if (file.isDirectory())
				return DrugFileModel.FILE_IS_DIRECTORY;
			/* ------------------------------------------------------ */
			
			// create a file reader
			FileInputStream drugFileReader = new FileInputStream(file
					.getAbsolutePath());
			this.drugCount = drugFileReader.available();
			
			// create a buffered reader for performance
			BufferedInputStream buffInput = new BufferedInputStream(drugFileReader);
			// create a DBFReader to read from the DBF File
			DBFReader dbfReader = new DBFReader(buffInput);

			/* ------------------------------------------------------ */
			// create the importer
			this.drugImporter = new ImportCefipDrug(dbfReader);

			// start the test
			if (drugImporter.testIntegrity()) {
				/* ------------------------------------------------------ */
//				drugFileReader.close();
				return DrugFileModel.FILE_OK;
				/* ------------------------------------------------------ */
			}
			else {
				/* ------------------------------------------------------ */
//				drugFileReader.close();
				return DrugFileModel.FILE_NOT_READABLE;
				/* ------------------------------------------------------ */
			}
			
		} catch (Exception e) {
			return DrugFileModel.FILE_NOT_READABLE;
		}
		/* ================================================== */
	}
	
	
	/**
	 * Deletes all manufacturers<br/>
	 * Should be called within an extra thread.
	 * Can take a while.
	 */
	public void deleteAllManufacturers() {
		/* ====================================================== */
		CefipDrugListModule.getManager().deleteAllManufacturer();
		/* ====================================================== */
	}
	
	/**
	 * Deletes all cefip drugs.
	 * <br/>Should be called within an extra thread. Can take long time
	 */
	public void deleteAllCefipDrugs() {
		/* ====================================================== */
//		CefipDrugListModule.getManager().deleteAdditionalSubstances();
		
		CefipDrugListModule.getManager().deleteAllCefipDrugData();
		/* ====================================================== */
	}
	
	
	
	/**
	 * @param file
	 * @return
	 */
	public Integer testManufacturer(File file) {
		/* ====================================================== */
		/* ---------------------------------------- */
		if (file.isDirectory())
			return DrugFileModel.FILE_IS_DIRECTORY;
		try {
			/* ------------------------------------------------------ */
			// create a file reader
			FileInputStream manuFileReader = new FileInputStream(file
					.getAbsolutePath());
			
			this.manuCount = manuFileReader.available();
			
			// create a buffered reader for performance
			BufferedInputStream buffInput = new BufferedInputStream(manuFileReader);
			// create a DBFReader to read from the DBF File
			DBFReader dbfReader = new DBFReader(buffInput);
	
			/* ------------------------------------------------------ */
			
			this.manufacturerImporter = new ImportCefipManufacturer(dbfReader);
			/* ------------------------------------------------------ */
			// test
	//		 start the test
			if (manufacturerImporter.testIntegrity()) {
				/* ------------------------------------------------------ */
//				dbfReader.close();
				return DrugFileModel.FILE_OK;
				/* ------------------------------------------------------ */
			}
			else {
				/* ------------------------------------------------------ */
//				dbfReader.close();
				return DrugFileModel.FILE_NOT_READABLE;
				/* ------------------------------------------------------ */
			}
			
		} catch (Exception e) {
			return DrugFileModel.FILE_NOT_READABLE;
		}
		/* ====================================================== */
	}
	
	/**
	 * Import the CefipManufacturers
	 * 
	 * @param file
	 * @param progressBar
	 */
	public void importManufacturer(JProgressBar progressBar, Integer version) {
		/* ====================================================== */
		if (version.equals(DrugFileModel.CEFIP_VERSION_OLD)) {
			/* ------------------------------------------------------- */
			if (manufacturerImporter != null) {
				manufacturerImporter.doImport(progressBar, manuCount);
			}
			/* ------------------------------------------------------- */
		} else
			if (version.equals(DrugFileModel.CEFIP_VERSION_2008)) {
				/* ------------------------------------------------------- */
				if (this.mdbManufactuerImporter == null) {
					/* ------------------------------------------------------- */
					logger.warn("no MdbManufacturer importer found");
					return;
					/* ------------------------------------------------------- */
				}
				/* ------------------------------------------------------- */
				this.mdbManufactuerImporter.doImport(progressBar, manuCount);
				/* ------------------------------------------------------- */
			}
		/* ====================================================== */
	}
	
	/**
	 * @param progressBar
	 */
	public void importCefipList(JProgressBar progressBar, Integer version) {
		/* ====================================================== */
		// save the date
		CefipDrugListModule.getManager().saveListDate(new Date());
		
		if (version.equals(DrugFileModel.CEFIP_VERSION_OLD)) {
			/* ------------------------------------------------------- */		
			this.drugImporter.doImport(progressBar, this.drugCount);
			/* ------------------------------------------------------- */
		} else
			if (version.equals(DrugFileModel.CEFIP_VERSION_2008)) {
				/* ------------------------------------------------------- */
				if (this.mdbDrugImporter == null) {
					/* ------------------------------------------------------- */
					logger.warn("no Mdb Drug importer found");
					return;
					/* ------------------------------------------------------- */
				}
				/* ------------------------------------------------------- */
				this.mdbDrugImporter.doImport(progressBar, this.drugCount);
				/* ------------------------------------------------------- */
			}
		/* ================================================== */
	}
	
	/**
	 * @param file
	 * @return
	 */
	public Integer testMdbFile(File file) {
		/* ====================================================== */
		if (file.isDirectory())
			return DrugFileModel.FILE_IS_DIRECTORY;
		/* ------------------------------------------------------- */
			
		this.mdbATCImporter 		= new ImportMdbATCClasses(file);
		this.mdbManufactuerImporter = new ImportMdbCefipManufacturer(file);
		this.mdbDrugImporter		= new ImportMdbCefipDrug(file);
		
		boolean atc  = this.mdbATCImporter.testIntegrity();
		boolean manu = this.mdbManufactuerImporter.testIntegrity();
		boolean drug = this.mdbDrugImporter.testIntegrity();
		
		this.atcCount = this.mdbATCImporter.getAmount();
		this.manuCount = this.mdbManufactuerImporter.getAmount();
		this.drugCount = this.mdbDrugImporter.getAmount();
		
		
		if (atc && manu && drug)
			return DrugFileModel.FILE_OK;
		else
			return DrugFileModel.FILE_NOT_READABLE;
		/* ------------------------------------------------------- */
		
		/* ====================================================== */
	}
	
	
	
	/**
	 * Tests if the file is present
	 * @param file
	 * @return
	 */
	public Integer testAtcFile(File file) {
		/* ====================================================== */
		/* ---------------------------------------- */
		if (file.isDirectory())
			return DrugFileModel.FILE_IS_DIRECTORY;
		try {
			/* ------------------------------------------------------ */
			// create a file reader
			FileInputStream atcFileReader = new FileInputStream(file
					.getAbsolutePath());
			
			this.atcCount = atcFileReader.available();
			
			// create a buffered reader for performance
			BufferedInputStream buffInput = new BufferedInputStream(atcFileReader);
			// create a DBFReader to read from the DBF File
			DBFReader dbfReader = new DBFReader(buffInput);
	
			/* ------------------------------------------------------ */
			
			this.atcImporter = new ImportATCClasses(dbfReader);
			/* ------------------------------------------------------ */
			// test
	//		 start the test
			if (atcImporter.testIntegrity()) {
				/* ------------------------------------------------------ */
//				dbfReader.close();
				return DrugFileModel.FILE_OK;
				/* ------------------------------------------------------ */
			}
			else {
				/* ------------------------------------------------------ */
//				dbfReader.close();
				return DrugFileModel.FILE_NOT_READABLE;
				/* ------------------------------------------------------ */
			}
			
		} catch (Exception e) {
			return DrugFileModel.FILE_NOT_READABLE;
		}
		/* ====================================================== */
	}
	
	
	/**
	 * Imports the atc classes shipped with the cefip list
	 * @param file
	 * @param progressBar
	 */
	public void importAtcClasses(JProgressBar progressBar, Integer version) {
		/* ====================================================== */
		if (version.equals(DrugFileModel.CEFIP_VERSION_OLD)) {
			if (this.atcImporter != null) {
				/* ------------------------------------------------------- */
				try {
					atcImporter.doImport(progressBar, this.atcCount);
				} catch (Exception e) {
					e.printStackTrace();
				}
				/* ------------------------------------------------------- */	
			}   
		} else 
			if (version.equals(DrugFileModel.CEFIP_VERSION_2008)) {
				/* ------------------------------------------------------- */
				if (this.mdbATCImporter == null) {
					/* ------------------------------------------------------- */
					logger.warn("no MdbAtc importer found");
					return;
					/* ------------------------------------------------------- */
				}
				/* ------------------------------------------------------- */
				this.mdbATCImporter.doImport(progressBar, atcCount);
				
				/* ------------------------------------------------------- */
			}
			
		/* ====================================================== */
	}
	
	
	/**
	 * Delete all atc classes
	 */
	public void deleteAllCefipAtcClasses() {
		/* ====================================================== */
		CefipDrugListModule.getManager().deleteAllCefipAtcClasses();
		/* ====================================================== */
	}
	
	/**
	 * Returns the current Cefip DrugList
	 * 
	 * @return
	 */
	public DrugList getList() {
		/* ====================================================== */
		return CefipDrugListModule.getManager().getList();
		/* ====================================================== */
	}


	public static void main (String[] args) {
		/* ================================================== */
		CefipImportWorker w = new CefipImportWorker();
		
		
		w.testMdbFile(new File("/home/heine/download/transfer/cefip/cefip2008.mdb"));
		
		/* ================================================== */
	}
	
	

}
