package com.armundia.core.startup;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.armundia.arm_am.entity.ApLang;
import com.armundia.arm_am.services.ApLangApp;
import com.armundia.generic.enums.Languages;

@ApplicationScoped
public class ApLangCacheMaintenance {
	private static Logger log = Logger.getLogger(ApLangCacheMaintenance.class.getName());

	@PersistenceContext
	protected EntityManager em;
	
	@PostConstruct
	public void initialize() {
		Languages.DEFAULT = Languages.ENGLISH;
		log.log(Level.INFO, String.format("ApLangCacheMaintenanceBase [hashCode] %s initializing ...", this.hashCode()));
		this.reload();
	}

	public void reload() {
		ApLangApp.getInstance().clear();

		Map<String, Map<String, String>> mapByLang;
		mapByLang = Collections.synchronizedMap(new HashMap<String, Map<String, String>>());

		Map<String, String> internalMap;
		internalMap = Collections.synchronizedMap(new HashMap<String, String>());

		Query q = em.createQuery("select f from ApLang f");
		@SuppressWarnings("unchecked")
		List<ApLang> lfrasi = (List<ApLang>) q.getResultList();
		
		Map<String, String> mapByLangTmp;
		String lang;
		String code;
		for (ApLang frase : lfrasi) {
			lang = frase.getId().getLang();
			code = frase.getId().getCode();
			internalMap.put(code + "@" + lang, frase.getDescr());

			mapByLangTmp = mapByLang.get(lang);
			if (mapByLangTmp == null) {
				mapByLangTmp = new HashMap<>();
				mapByLang.put(lang, mapByLangTmp);
			}
			mapByLangTmp.put(code, frase.getDescr());
		}

		ApLangApp.getInstance().initialize(internalMap, mapByLang);
	}
	
	@PreDestroy
	public void destroy() {
		ApLangApp.destroy();
	}
}
