package it.micegroup.gestioneferie.libs.utilities;

import java.util.List;
import java.util.Locale;

import org.springframework.context.MessageSource;
import org.springframework.context.support.DefaultMessageSourceResolvable;

import it.micegroup.voila2runtime.response.Message;
import it.micegroup.voila2runtime.response.Message.MessageLevelType;


public class MessageUtil {
	private static MessageSource messageSource;
	private static ThreadLocal<List<Message>> messages = new ThreadLocal<>();
	
	public static void setMessageSource(MessageSource source) {
		messageSource = source;
	}

	public static ThreadLocal<List<Message>> getThreadLocalMessages() {
		return messages;
	}

	public static void setThreadLocalMessages(ThreadLocal<List<Message>> messages) {
		MessageUtil.messages = messages;
	}

	public static List<Message> getMessages() {
		return getThreadLocalMessages().get();
	}
	
	public static void setMessages(List<Message> msgs) {
		getThreadLocalMessages().set(msgs);
	}

	public static Message addInfoMessage(String msg) {
		return addMessage(MessageLevelType.INFO, null, msg, null);
	}

	public static Message addInfoMessage(String key, Object ... args) {
		return addMessage(MessageLevelType.INFO, key, null, args);
	}

	public static Message addWarningMessage(String msg) {
		return addMessage(MessageLevelType.WARNING, null, msg, null);
	}

	public static Message addWarningMessage(String key, Object ... args) {
		return addMessage(MessageLevelType.WARNING, key, null, args);
	}

	public static Message addErrorMessage(String msg) {
		return addMessage(MessageLevelType.ERROR, null, msg, null);
	}

	public static Message addErrorMessage(String key, Object ... args) {
		return addMessage(MessageLevelType.ERROR, key, null, args);
	}

	public static Message addMessage(MessageLevelType severity, String key, String msg, Object[] args) {
		if (key != null) {
			String[] fields = new String[args.length];
			if (args.length > 0 && args[0].getClass().isAssignableFrom(DefaultMessageSourceResolvable.class)) {
				for (int i = 0; i < args.length; i++) {
					if (DefaultMessageSourceResolvable.class.isAssignableFrom(args[i].getClass())) {
						fields[i] = messageSource.getMessage((DefaultMessageSourceResolvable)args[i], Locale.getDefault());
					}
				}
				msg = messageSource.getMessage(key, fields, msg, Locale.getDefault());
			} else {
				msg = messageSource.getMessage(key, args, msg, Locale.getDefault());
			}
		}
		Message m = new Message(severity, key, msg, args);
		getMessages().add(m);
		return m;
	}
}

