package com.rjconsultores.ventaboletos.web.utilerias.render;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;

import javax.persistence.Id;

import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;

import com.google.gson.Gson;
import com.rjconsultores.ventaboletos.auditoria.AuditControl;
import com.rjconsultores.ventaboletos.entidad.AuditLog;
import com.rjconsultores.ventaboletos.enums.auditoria.EnumAuditAction;

public class RenderEntityDetail implements ListitemRenderer {
	
	@Override
	public void render(Listitem item, Object object) throws Exception {
		
		AuditLog auditLog = (AuditLog) object;
		Listcell lc = new Listcell();
		
		Gson gson = AuditControl.getGson();
		Class<?> clazz = Class.forName("com.rjconsultores.ventaboletos.entidad.".concat(auditLog.getEntityName()));

		Object clazzJson = gson.fromJson(auditLog.getEntityDetail(), clazz);
		
		for (Field field: clazzJson.getClass().getDeclaredFields()) {
			
			if (!field.isAnnotationPresent(Id.class)) {
				continue;
			}
			
			field.setAccessible(true);
			
			lc = new Listcell((field.get(clazzJson) == null ? "null" : field.get(clazzJson)).toString());
			lc.setParent(item);		
			
			break;
		}
		
		lc = new Listcell(auditLog.getUsuario().getNombusuario());
		lc.setParent(item);				
		
		lc = new Listcell(auditLog.getSistema().getNombsistema());
		lc.setParent(item);				
		
		SimpleDateFormat sdf = new SimpleDateFormat();
		sdf.applyPattern("dd/MM/yyyy");

		lc = new Listcell(sdf.format(auditLog.getCreatedDate()));
		lc.setParent(item);		
		
		lc = new Listcell(EnumAuditAction.findAction(auditLog.getAction()));
		lc.setParent(item);
	}
}
