package com.fp.bpmlib.query.monitor;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Map;

import javax.persistence.Query;

import org.apache.log4j.Logger;

import com.fp.dto.json.Serializer;
import com.fp.dto.save.SaveRequest;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.exception.CommondbException;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.pbpm.gene.TbpmActivities;
import com.fp.persistence.pbpm.gene.TbpmActivitiesKey;
import com.fp.simple.dto.TaskInfo;

/**
 * 
 * @author GBC
 *
 */
public class FlowActivitySave {

	/**
     * Logger
     */
    private static final Logger LOG = Logger.getLogger(FlowActivitySave.class);
    
    /**
     * JPQL TAREA_SUMMARY
     */
    private static final String TAREA_SUMMARY = "select t from BAMTaskSummaryImpl t where t.taskId = :idtarea";

	/*
	 * 	Nombre             Nulo     Tipo          
		------------------ -------- ------------- 
		JOURNALID          NOT NULL VARCHAR2(50)  --maia
		ACTIVITYNAME       NOT NULL VARCHAR2(100) --taskdata
		SEQUENCE           NOT NULL NUMBER(5)     --Id de la tarea
		USERCODE                    VARCHAR2(20)  -- taskdata usuario responsable //update para actualizar el usuario
		GROUPCODE                   VARCHAR2(30)  -- //grupo de la tarea taskinfo
		COMPANYCODE                 NUMBER(10)    -- maia***no se encontro
		ACTION                      VARCHAR2(50)  --vacio
		ADITIONALDATA               CLOB          --taskinfo //actualizar al completar la tarea
		COMPLETED                   TIMESTAMP(6)  -- se actualiza al completar la tarea
		CREATED                     TIMESTAMP(6)  -- taskdata
		EXPECTEDTIME                NUMBER       -- taskinfo	 
		TASKJOURNALID               VARCHAR2(50)  -- revisar en el taskcomplete
		RESPONSE                    VARCHAR2(50)  -- taskcomplete
		RULECODE                    VARCHAR2(30)  
		RULECODEDEFAULT             VARCHAR2(30)  
		STARTED                     TIMESTAMP(6)-- actualizar en el start
		TASKID                      NUMBER        --en el metodo del handles
		MODULE                      VARCHAR2(50)  -- taskinfo
		TRANSACTION                 NUMBER       --taskinfo 
		VERSION                     NUMBER        --taskinfo
		INTERNALCODE                VARCHAR2(50)  -- usar el PID 
		PACKAGENAME                 VARCHAR2(120) 
		PACKAGENAMEDEFAULT          VARCHAR2(120)  
	 */
       
	 /**
	     * Manage activity.
	     * 
	     * @param pTaskInfo the task info
	     * @param pActivityname the activityname
	     * @param pSequence the sequence
	     * @throws Exception la exception
	     */
	    public static void crearActivity(Map<String, Object> mparam, TaskInfo taskInfo, long idTarea, java.util.Date onCreated) throws Exception {
	        //(mparam.get("journalid"), pActivityname, pSequence);
	        SaveRequest saveRequest = (SaveRequest) mparam.get("request"); 
	        TbpmActivitiesKey k = new TbpmActivitiesKey(saveRequest.getJournalId(), taskInfo.getTname(),new Integer(mparam.get("PID").toString()));
	        TbpmActivities act = new TbpmActivities();
	        act.setPk(k);

	        if (taskInfo.getAditionalData() != null) {
	            Serializer ser = new Serializer((Serializable) taskInfo.getAditionalData());
	            act.setAditionaldata(ser.toJSON());
	        }
	        act.setGroupcode(taskInfo.getGroupId());
	        act.setUsercode(taskInfo.getUserId());
	        //act.setCompanycode(mparam.get(key));
	        act.setCreated(new Timestamp(onCreated.getTime()));
	        act.setExpectedtime(taskInfo.getExpectedTime());
	        act.setTaskjournalid(taskInfo.getJournalId());
	        act.setTaskid(idTarea);
	        act.setRulecode(taskInfo.getRuleCode());
	        act.setRulecodedefault(taskInfo.getRuleCodeDefault());
	        act.setInternalcode(mparam.get("PID").toString());
	        act.setVersion(taskInfo.getVersion().longValue());
	        act.setModule(taskInfo.getModule());
	        act.setTransaction(taskInfo.getTransaction().longValue());
	       
	        PersistenceHelper.saveOrUpdate(act);
	 

	    }
	    
	    /***
	     * Metodo que actualiza la informacion cuando esta es asignada a un usuario
	     * @param idTarea
	     * @param userCode
	     * @throws CommondbException
	     * @throws Exception
	     */
	    public static void actualizarActividadClaim(long idTarea, String userCode) throws CommondbException, Exception{
	    	Query q = PersistenceHelper.getEntityManager().createQuery("from TbpmActivities p where p.taskid=:idTarea");
	        q.setParameter("idTarea", idTarea);
	        TbpmActivities act = (TbpmActivities) q.getSingleResult();
	        act.setUsercode(userCode);
	        PersistenceHelper.saveOrUpdate(act);
	    	
	    }
	    
	    /***
	     * Metodo que actualiza la informacion cuando esta es seleccionada por el usuario
	     * @param idTarea
	     * @throws CommondbException
	     * @throws Exception
	     */
	    public static void actualizarActividadStart(long idTarea) throws CommondbException, Exception{
	    	Query q = PersistenceHelper.getEntityManager().createQuery("from TbpmActivities p where p.taskid=:idTarea");
	        q.setParameter("idTarea", idTarea);
	        TbpmActivities act = (TbpmActivities) q.getSingleResult();
	        act.setStarted(FormatDates.getInstance().getDataBaseTimestamp());
//	        act.setTaskjournalid(taskInfo.getJournalId());
	        PersistenceHelper.saveOrUpdate(act);
	    	
	    }
	    
	    /***
	     * Metodo que actualiza la informacion de la tarea cuando esta es completada.
	     * @param idTarea
	     * @param taskInfo
	     * @throws CommondbException
	     * @throws Exception
	     */
	    public static void actualizarActividadComplete(long idTarea, TaskInfo taskInfo) throws CommondbException, Exception{
	    	Query q = PersistenceHelper.getEntityManager().createQuery("from TbpmActivities p where p.taskid=:idTarea");
	        q.setParameter("idTarea", idTarea);
	        TbpmActivities act = (TbpmActivities) q.getSingleResult();
	        act.setCompleted(FormatDates.getInstance().getDataBaseTimestamp());
	        act.setTaskjournalid(taskInfo.getJournalId());
	        act.setResponse(taskInfo.getResponse());
	        PersistenceHelper.saveOrUpdate(act);
	    	
	    }
	    
	    /**
	     * Metodo q actualiza el usuario cuando esta tarea es reasignada
	     * @param idTarea
	     * @param userCode
	     * @throws CommondbException
	     * @throws Exception
	     */
	    public static void actualizarActividadDelegate(long idTarea, String userCode) throws CommondbException, Exception{
	    	Query q = PersistenceHelper.getEntityManager().createQuery("from TbpmActivities p where p.taskid=:idTarea");
	        q.setParameter("idTarea", idTarea);
	        TbpmActivities act = (TbpmActivities) q.getSingleResult();
	        act.setUsercode(userCode);
	        PersistenceHelper.saveOrUpdate(act);
	    	
	    }
	  
}
