package com.eactive.eai.transformer.util;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

import org.apache.commons.collections.buffer.CircularFifoBuffer;

import com.eactive.eai.common.util.Logger;


public class CircularQueue extends CircularFifoBuffer {
	final static Logger logger = Logger.getLogger("transformer");

	final static long AGE = 1000L * 60 * 60 * 24;   // 1 day
	final static DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM-dd HH:mm:ss");
	
	private final String LOG_PREFIX = "CircularQueue | ";
	public CircularQueue(int maxSize) {
		super(maxSize);
	}
    
    public synchronized boolean add(Object o) {
    	try {
    		return super.add(o);
    	} catch(Exception e) {
			super.clear();
    		logger.warn(LOG_PREFIX + e.getMessage());
    		return true;
    	}
    }
    
	public synchronized void addRecord(String recordData) {
    	try {
			super.add(new Tuple(System.currentTimeMillis(), recordData));
		} catch(Exception e) {
			super.clear();
			logger.warn(LOG_PREFIX + e.getMessage());
		}
	}
	
	public synchronized int getRecordCount() {
		clearOldRecords();
		return size();
	}

	public synchronized String[]getRecords() {
		clearOldRecords();
		
        Object[] elements = toArray();
        String[] errors = new String[elements.length];
    	for (int i=0; i<elements.length; i++) {
    		errors[i] = getDateFormat(((Tuple) elements[i]).getTime()) + ((Tuple) elements[i]).getMessage();
    	}
		return errors;
	}
	public String getDateFormat(long time){
		Instant instant = Instant.ofEpochMilli(time);
		ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
		return "["+dateFormat.format(zdt)+"] - ";
	}
	
	private synchronized void clearOldRecords() {
		try {
	        Object[] elements = toArray();
	    	for (int i=0; i<elements.length; i++) {
	    		Tuple tuple = (Tuple) elements[i];
	    		if (tuple != null && System.currentTimeMillis() - tuple.getTime() > AGE) {
	    			this.remove(tuple);
	    		}
	    	}
		} catch(Exception e) {
			super.clear();
			logger.warn(LOG_PREFIX + e.getMessage());
		}
	}
	
	public static class Tuple {
		long   time;
		String message;
		
		public Tuple(long time, String message) {
			this.time = time;
			this.message = message;
		}
		
		public long getTime() {
			return time;
		}
		
		public String getMessage() {
			return message;
		}
	}
	
    public String toString() {
    	StringBuilder sb = new StringBuilder();
    	sb.append(LOG_PREFIX + "max:" + maxSize() + " size:" + size() + "\n");
        sb.append("---------------------------------------------------------------------------------------------------------------------\n");
        Object[] elements = toArray();
    	for (int i=elements.length-1; i>=0; i--) {
    		if (elements[i] == null)
    			continue;
    		sb.append(((String) elements[i]) + "\n");
    	}
        sb.append("---------------------------------------------------------------------------------------------------------------------\n");
    	return sb.toString();
    }
}
