package com.myeclipseide.batch;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;

@Singleton
@Startup
public class SampleDataHolderBean {

	private static Logger LOGGER = Logger.getLogger(SampleDataHolderBean.class
			.getName());
	private Map<String, Set<PayrollInputRecord>> payrollInputRecords = new HashMap<>();

	private Map<String, Set<PayrollRecord>> payrollRegistry = new HashMap<>();

	@PostConstruct
	public void onApplicationStartup() {
		// read pay roll input details from csv
		BufferedReader reader = null;
		try {
			InputStream ins = this.getClass().getClassLoader()
					.getResourceAsStream(PayRollConstants.SALDATA_CSV_PATH);
			reader = new BufferedReader(new InputStreamReader(ins));
			String line;
			while ((line = reader.readLine()) != null) {
				String[] tokens = line.split("[, \t\r\n]+");
				String yearMonth = tokens[0];
				Set<PayrollInputRecord> records = payrollInputRecords
						.get(yearMonth);
				PayrollInputRecord record = new PayrollInputRecord();
				record.setId(Integer.parseInt(tokens[1]));
				record.setBaseSalary(Integer.parseInt(tokens[2]));
				if (records == null) {
					records = new HashSet<>();
					payrollInputRecords.put(yearMonth, records);
				}
				records.add(record);
			}
		} catch (FileNotFoundException e) {
			throw new PayRollAppException(e);
		} catch (IOException e) {
			throw new PayRollAppException(e);
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}

			} catch (IOException e) {
				LOGGER.severe("Could not close reader for "
						+ PayRollConstants.SALDATA_CSV_PATH);
			}

		}

	}

	
	public String[] getAllMonthYear() {
		return payrollInputRecords.keySet().toArray(new String[0]);
	}

	public Set<PayrollInputRecord> getPayrollInputRecords(String monthYear) {
		return payrollInputRecords.get(monthYear);
	}

	public void addPayrollRecord(PayrollRecord r) {
		String monthYear = r.getMonthYear();
		Set<PayrollRecord> monthlyPayroll = payrollRegistry.get(monthYear);
		if (monthlyPayroll == null) {
			monthlyPayroll = new HashSet<>();
			payrollRegistry.put(monthYear, monthlyPayroll);
		}
		monthlyPayroll.add(r);
	}

	public Set<PayrollRecord> getPayrollRecords(String monthYear) {
		Set<PayrollRecord> empty = new HashSet<>();
		Set<PayrollRecord> records = payrollRegistry.get(monthYear);
		return records == null ? empty : records;
	}

	public void clear() {
		payrollInputRecords.clear();
		payrollRegistry.clear();

	}
}
