package com.eactive.eai.rms.common.acl.audit.adapter.out.file;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.web.context.ServletContextAware;

import com.eactive.eai.rms.common.acl.audit.domain.AuditPoint;

public class AuditPointsFactoryBean implements FactoryBean<Map<String, AuditPoint>>, ServletContextAware {

	private Map<String, AuditPoint> points = new HashMap<>();
	private String filePath;
	private ServletContext servletContext;

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	@Override
	public Map<String, AuditPoint> getObject() throws Exception {
		try (BufferedReader br = new BufferedReader(
				new InputStreamReader(servletContext.getResourceAsStream(filePath), "UTF-8"))) {
			String line;
			while ((line = br.readLine()) != null) {
				String[] parts = line.split("_");
				if (parts.length == 4) {
					String logType = parts[0];
					String logTypeText = parts[1];
					String[] systemCodes = parts[2].split(",");
					String[] commands = parts[3].split(",");
					for (String systemCode : systemCodes) {
						for (String command : commands) {
							AuditPoint point = new AuditPoint(systemCode, logType, command, logTypeText);
							String key = AuditPoint.generateKey(logType, systemCode, command);
							points.put(key, point);
						}
					}
				}
			}
		} catch (IOException e) {
			throw new AuditPointsFileNotExistException("Error reading audit points file", e);
		}
		return points;
	}

	@Override
	public Class<?> getObjectType() {
		return Map.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}
}
