package com.eactive.eai.rms.onl.manage.serviceinfo.itsm.vo;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;

@XmlRootElement(name = "errorEvent")
@XmlAccessorType(XmlAccessType.FIELD)
public class ErrorEvent {

	private String status;

	@XmlElement(name = "error")
	private List<ItsmError> errorList = null;
	
	public ErrorEvent() { }

	public ErrorEvent(HashMap<String, HashMap<String, String>> allErrorMap) {
		
		this.errorList = new ArrayList<>();
		
		if (!allErrorMap.isEmpty()) {
			
			allErrorMap.forEach((key, map) -> errorList.add(new ItsmError(map)));
			
			setErrorCodeBAT_BAP(errorList);
			
			BATtoEBT_BAPtoFBT(errorList);
			
			replaceBracketMessge(errorList);
			
			this.errorList = sortByTime(errorList);
			
		} else {
			
			this.status = "NO_ERROR";
			
		}
		
	}

	private void setErrorCodeBAT_BAP(List<ItsmError> errorList) {
		
		// TODO - 회의 후 추가
		
	}

	private void BATtoEBT_BAPtoFBT(List<ItsmError> errorList) {
		
		errorList.forEach(itsmError -> {
			if(Optional.ofNullable(itsmError.getServiceCode()).orElse("NULL_OPTION").equals(DataSourceTypeManager.BAT)) {
				itsmError.setServiceCode("EBT");
			} else if(Optional.ofNullable(itsmError.getServiceCode()).orElse("NULL_OPTION").equals(DataSourceTypeManager.BAP)) {
				itsmError.setServiceCode("FBT");
			}
		});
	}
	
	private void replaceBracketMessge(List<ItsmError> errorList) {
		
		errorList.forEach(itsmError -> {
			itsmError.setErrorMessage(itsmError.getErrorMessage().replaceAll("\\[(.*)\\](\\s*)", ""));
		});
	}
	
	private List<ItsmError> sortByTime(List<ItsmError> errorList) {
		
		return errorList.stream().sorted(Comparator.comparing(ItsmError::getErrorYms)).collect(Collectors.toList());
	}
	
	private List<ItsmError> sortByTimeReversed(List<ItsmError> errorList) {
		
		return errorList.stream().sorted(Comparator.comparing(ItsmError::getErrorYms).reversed()).collect(Collectors.toList());
	}

	public void add(ItsmError error) {
		this.errorList.add(error);
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public List<ItsmError> getErrorList() {
		return errorList;
	}

	public void setErrorList(List<ItsmError> errorList) {
		this.errorList = errorList;
	}

}
