/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.queplix.qwoss.notification;

import com.queplix.core.error.ErrorHelper;
import com.queplix.core.integrator.security.AccessRightsManager;
import com.queplix.core.integrator.security.LogonSession;
import com.queplix.core.integrator.security.User;
import com.queplix.core.integrator.security.WorkGroup;
import com.queplix.core.jxb.entity.Entity;
import com.queplix.core.modules.eql.CompoundKey;
import com.queplix.core.modules.eql.ejb.EQLManagerLocal;
import com.queplix.core.modules.eql.error.EQLException;
import com.queplix.core.modules.eqlext.GetRecordsRes;
import com.queplix.core.modules.eqlext.ejb.GetRecordsLocal;
import com.queplix.core.modules.eqlext.ejb.GetRecordsLocalHome;
import com.queplix.core.modules.eqlext.jxb.gr.Req;
import com.queplix.core.modules.eqlext.jxb.gr.ReqEntity;
import com.queplix.core.modules.eqlext.jxb.gr.ReqFilter;
import com.queplix.core.modules.eqlext.jxb.gr.ReqFilters;
import com.queplix.core.modules.eqlext.jxb.gr.ReqFiltersTypeItem;
import com.queplix.core.modules.eqlext.jxb.gr.Reqs;
import com.queplix.core.modules.eqlext.jxb.gr.Ress;
import com.queplix.core.modules.jeo.JEObject;
import com.queplix.core.modules.jeo.ejb.JEOManagerLocal;
import com.queplix.core.utils.JNDINames;
import com.queplix.qwoss.gen.CustomerObjectHandler;
import com.queplix.qwoss.gen.EmployeeObjectHandler;
import com.queplix.qwoss.gen.EscPriorityFieldObject;
import com.queplix.qwoss.gen.EscPriorityFieldObjectHandler;
import com.queplix.qwoss.gen.EscRecipientFieldObject;
import com.queplix.qwoss.gen.EscRecipientFieldObjectHandler;
import com.queplix.qwoss.gen.EscStatusFieldObject;
import com.queplix.qwoss.gen.EscStatusFieldObjectHandler;
import com.queplix.qwoss.gen.TicketEscalationObject;
import com.queplix.qwoss.gen.TicketEscalationObjectHandler;
import com.queplix.qwoss.gen.TicketEsclEventObject;
import com.queplix.qwoss.gen.TicketEsclEventObjectHandler;
import com.queplix.qwoss.gen.TicketObject;
import com.queplix.qwoss.gen.TicketObjectHandler;
import com.queplix.qwoss.utils.ApplicationHelper;
import com.queplix.qwoss.utils.TicketEscalationHelper;
import com.queplix.qwoss.utils.TicketHelper;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Ticket Escalations Manager EJB.
 *
 * @author [ALB] Baranov Andrey
 * @version $Revision: 1.7.2.2 $ $Date: 2005/12/20 16:43:05 $
 */
public class TicketEscalationManagerEJB
        extends
        AbstractEntityEscalationManagerEJB {

    private static final String PRODUCT_ENTITY = "product";
    private static final String PRODUCT_EFIELD_ID = "qw_product";
    private static final String PRODUCT_EFIELD_NAME = "qw_name";

    /**
     * Initializes bean.
     */
    public void ejbCreate() {
        INFO("TicketEscalationManagerEJB create - " + hashCode());
    }

    /**
     * Generates ticket escalation events for the given ticket.
     *
     * @param ls        LogonSession object
     * @param entityJEO ticket JEO object
     */
    public void generateEvents(LogonSession ls, Object entityJEO) {
        
        long time = System.currentTimeMillis();
        
        //INFO message
        infoMsg(entityJEO);
        Long ticketId = getTicketID(entityJEO); 
        try {
            // Initialization.
            JEOManagerLocal jeoManager = getJEOManagerLocal();
            // Find All ticket escalations.
            List escalations = getEscalationList( jeoManager, ls);
            // For all selected escalations...
            int size = (escalations != null) ? escalations.size():0;
            for(int i = 0; i < size; i++) {
                TicketEscalationObjectHandler escHnd = (TicketEscalationObjectHandler) escalations.get(i);
                TicketEscalationObject escObj = (TicketEscalationObject) escHnd.getJEObject();
                
                // 1 Check, if event already exists.
                List events = TicketEsclEventObjectHandler.selectByEscalationAndTicket(
                        jeoManager, ls, escObj.getQw_escalationid(), ticketId);
                if(events != null) {
                    if(getLogger().isDebugEnabled()) {
                        DEBUG("Events for the ticket (ID = "+ ticketId + ") already exist...");
                        DEBUG("Try to remove obsolete...");
                    }
                    // Try to remove obsolete events.
                    removeObsoleteEsclEvents(entityJEO, escObj, events);
                    continue;
                }
                
                // 2. Check, if ticket and escalation parameters equal.
                // If a check failed - go to the next escalation.
                if(!equals(ls, entityJEO, escObj)) {
                    continue;
                }

                // 3 If check was ok and esclation event record not exist,
                // create a new event.
                TicketEsclEventObjectHandler eventHnd = (TicketEsclEventObjectHandler) 
                        jeoManager.create(ls, TicketEsclEventObjectHandler.class);
                TicketEsclEventObject eventObj = (TicketEsclEventObject) eventHnd.getJEObject();
                eventObj.setQw_escalationid(escObj.getQw_escalationid());
                eventObj.setQw_ticketid(ticketId);
                eventObj.setQw_next_check(getNextCheckDate(escObj.getQw_waittime(), escObj.getQw_timeunit()));

                if(escObj.getQw_fireif() == getNotUpdatedFireIf()) {
                    // Remember DateModified for this type of FireIf
                    eventObj.setQw_datemodified(getTicketDateModified(entityJEO));
                }
                eventHnd.commit();

                DEBUG("New ticket escalation event was created:"
                        + "\n\t event ID = "
                        + eventObj.getQw_esceventid()
                        + "\n\t escalation ID = "
                        + eventObj.getQw_escalationid()
                        + "\n\t ticket ID = "
                        + eventObj.getQw_ticketid()
                        + "\n\t last modified = "
                        + eventObj.getQw_datemodified());
            } // for

        } catch (EQLException ex) {
            throwException(ex);

        } catch (Throwable t) {
            ErrorHelper.throwSystemException(t, this);
        }

        // Ok.
        INFO("Escalation events for the ticket (ID = " + ticketId + ") were generated successfully.");
        INFO("Time (ms) - " + (System.currentTimeMillis() - time));
    }

    /**
     * Fires ticket escalation events.
     *
     * @return number of fired events
     */
    public int fireEvents() {

        long time = System.currentTimeMillis();
        INFO("Firing ticket escalation events...");

        int eventsCount = 0;

        try {
            // Initialization.
            JEOManagerLocal jeoManager = getJEOManagerLocal();
            LogonSession ls = AccessRightsManager.getSystemLogonSession();

            Entity entity = loadTicketEntity();

            // Find matured ticket escalation events.
            List esclEventObjectList = TicketEsclEventObjectHandler.selectMatured(jeoManager, ls);

            // For all selected events...
            int size = (esclEventObjectList != null) ? esclEventObjectList.size():0;
            for(int i = 0; i < size; i++) {
                TicketEsclEventObjectHandler eventHnd = (TicketEsclEventObjectHandler)esclEventObjectList.get(i);
                TicketEsclEventObject eventObj = (TicketEsclEventObject) eventHnd.getJEObject();
                Long eventID = eventObj.getQw_esceventid();
                DEBUG("Firing the ticket escalation event (ID = " + eventID + ")");

                // 1. Get escalation JEO object.
                Long escID = eventObj.getQw_escalationid();
                TicketEscalationObjectHandler escHnd = getTicketEscalationObjectHandler(jeoManager, ls, escID);
                // If no escalation was found, remove the event.
                if(escHnd == null) {
                    WARN("Escalation is not found for the event (ID = " + eventID + ") - removing...");
                    eventHnd.remove();
                    eventHnd.commit();
                    continue;
                }
                TicketEscalationObject escObj = (TicketEscalationObject) escHnd.getJEObject();
                // If disabled - remove event.
                if(escObj.getQw_disable() == 1) {
                    WARN("Escalation is disabled for the event (ID = " + eventID + ")");
                    eventHnd.remove();
                    eventHnd.commit();
                    continue;
                }
                // If the esclation is repeatable, calculate its next check date.
                boolean repeatedEscalation = (escObj.getQw_repeat() != null)
                        && (escObj.getQw_repeat() == 1) && (escObj.getQw_waittime() > 0);
                Date nextCheckDate = null;
                if(repeatedEscalation) {
                    nextCheckDate = getNextCheckDate(escObj.getQw_waittime(), escObj.getQw_timeunit());
                }

                // 2. Get ticket JEO object.
                Long ticketID = eventObj.getQw_ticketid();
                JEObject entityJEO = getJEObjectById(jeoManager, ls, ticketID);
                
                // If no ticket found, remove the event.
                if(entityJEO == null) {
                    if(getLogger().isInfoEnabled()) {
                        WARN("Ticket is not found for the event (ID = " + eventID + ") - removing...");
                    }
                    eventHnd.remove();
                    eventHnd.commit();
                    continue;
                }

                // 3. Check escalation and ticket attributes.

                // If a check failed - remove the event.
                if(!equals(ls, entityJEO, escObj)) {
                    WARN("Escalation (ID = " + escID + ") is inconsistent with ticket " + "(ID = "
                            + ticketID + ") - removing the event...");
                    eventHnd.remove();
                    eventHnd.commit();
                    continue;
                }

                // Check escalation 'FireIf'.
                if(checkFireif(entityJEO, escObj, eventObj)) {

                    // 4. Do notification.
                    
                    // Initialize compound key.
                    CompoundKey key = new CompoundKey();
                    key.addKey(String.valueOf(getTicketID(entityJEO)));

                    // Initialize Notification Manager EJB.
                    NotificationManagerLocal notificationLocal = getNotificationManagerLocal(ls, entity, key);

                    notificationLocal.setSubject(escObj.getQw_subject());
                    notificationLocal.setMessage(
                            (escObj.getQw_mailbody() == null) ? null : new String(escObj.getQw_mailbody()));

                    // determine the recipient email
                    // Check recipient

                    List<EscRecipientFieldObjectHandler> escRecipientHandlers = EscRecipientFieldObjectHandler
                            .selectByEscalationId(jeoManager, ls, escObj.getQw_escalationid());

                    // for all recipients do --
                    if(escRecipientHandlers != null) {
                        for(EscRecipientFieldObjectHandler escRecipientFieldObjectHandler : escRecipientHandlers) {
                            EscRecipientFieldObject escRecipientFieldObject =
                                    (EscRecipientFieldObject) escRecipientFieldObjectHandler.getJEObject();
                            Integer recipinet = escRecipientFieldObject.getQw_recipient();
                            if(recipinet == null) {
                                WARN("Escalation (ID = " + escID + ") is canceled. Recipient is needed.");
                                eventHnd.remove();
                                eventHnd.commit();
                                continue;
                            }
                            switch(recipinet) {
                                case TicketEscalationHelper.ASSIGNED_WORKGROUP_RECIPIENT:
                                    Long workGroupId = escObj.getQw_workgroupid();
                                    if(workGroupId == null) {
                                        WARN("Escalation (ID = " + escID + 
                                             ") is canceled. Assigned workgroup is needed.");
                                        eventHnd.remove();
                                        eventHnd.commit();
                                        continue;
                                    }
                                    WorkGroup recWorkGroup = loadNotifiedGroup(ls, workGroupId);
                                    if(recWorkGroup == null) {
                                        WARN("Escalation (ID = " + escID + ") is canceled. "+
                                             "Can't load the workgroup with ID " + workGroupId + ".");
                                        eventHnd.remove();
                                        eventHnd.commit();
                                        continue;
                                    }
                                    notificationLocal.notify(recWorkGroup, null, null);
                                    break;
                                case TicketEscalationHelper.ASSIGNED_EMPLOYEE_RECIPIENT:
                                    Long employeeId = escObj.getQw_employeeid();
                                    if(employeeId == null) {
                                        WARN("Escalation (ID = " + escID
                                                + ") is canceled. Assigned employee is needed.");
                                        eventHnd.remove();
                                        eventHnd.commit();
                                        continue;
                                    }
                                    User recEmployee = loadEmployee(ls, employeeId);
                                    if(recEmployee == null) {
                                        WARN("Escalation (ID = " + escID + ") is canceled. "+
                                             "Can't load the employee with ID " + employeeId + ".");
                                        eventHnd.remove();
                                        eventHnd.commit();
                                        continue;
                                    }
                                    Integer notifType = escObj.getQw_sendmode();
                                    if(notifType == null) {
                                        notificationLocal.notify(recEmployee);
                                    } else {
                                        switch(notifType) {
                                            case TicketEscalationHelper.ALERT_METHOD:
                                                notificationLocal.notifyByAlert(recEmployee);
                                                break;
                                            case TicketEscalationHelper.EMAIL_METHOD:
                                                notificationLocal.notifyByMail(recEmployee);
                                                break;
                                        }
                                    }
                                    break;
                                case TicketEscalationHelper.ASSIGNED_EMAIL_RECIPIENT:
                                    String email = escObj.getQw_email();
                                    if(email == null) {
                                        WARN("Escalation (ID = " + escID
                                                + ") is canceled. Assigned email is needed.");
                                        eventHnd.remove();
                                        eventHnd.commit();
                                        continue;
                                    }
                                    notificationLocal.notifyByMail(email);
                                    break;
                            }
                        }
                    }

                    // Event is fired - count it.
                    eventsCount++;

                }

                // 5. Update next check date or remove event

                if(!repeatedEscalation) {
                    // Remove event
                    DEBUG("Removing the event (ID = " + eventID + ")...");
                    eventHnd.remove();
                    eventHnd.commit();
                } else {
                    // Update event
                    DEBUG("Updating the event (ID = " + eventID + ")...");
                    eventObj.setQw_next_check(nextCheckDate);
                    eventHnd.commit();
                }

            } // for

        } catch (EQLException ex) {
            throwException(ex);

        } catch (Throwable t) {
            ErrorHelper.throwSystemException(t, this);
        }

        // Ok.
        INFO("Ticket escalation events successfully fired.");
        INFO("Fired " + eventsCount + " events, at " + (System.currentTimeMillis() - time) + " ms.");
        return eventsCount;
    }

    //
    // Remove obsolete escalation events.
    //

    private void removeObsoleteEsclEvents(Object entityJEO, TicketEscalationObject escObj,
                                          List events)
            throws EQLException {
        // Check events in cycle.
        int count = 0;
        int size = (events == null) ? 0:events.size();
        for(int i3 = 0; i3 < size; i3++) {
            TicketEsclEventObjectHandler eventHnd = (TicketEsclEventObjectHandler) events.get(i3);
            TicketEsclEventObject eventObj = (TicketEsclEventObject) eventHnd.getJEObject();
            // remove only those events where Escalation Fireif is 'Not Updated'
            // but Ticket Modified Date is greater than event's or
            // where Escalation Fireif is 'Not Closed' but Ticket Type is CLOSED or
            // where Escalation Fireif is 'Not Assigned' but Ticket Type is not NEW
            if(checkFireif(entityJEO, escObj, eventObj)) {
                continue;
            }
            eventHnd.remove();
            eventHnd.commit();
            count++;
        }
        // Ok.
        INFO("Removed " + count + " obsolete ticket escalation events for ticket #" + getTicketID(entityJEO));
    }

    //
    // Calculates event's next check date.
    //
    private Date getNextCheckDate(Long delay, Integer delayUnits) {
        // Check arguments.
        if(delayUnits == null) {
            throw new IllegalStateException("Delay unitis null.");
        }
        // Switch by time unit.
        switch(delayUnits) {
            case TicketEscalationHelper.MINUTES_DELAY_UNITS:
                return getNextCheckDate(delay, Calendar.MINUTE);
            case TicketEscalationHelper.HOURS_DELAY_UNITS:
                return getNextCheckDate(delay, Calendar.HOUR);
            case TicketEscalationHelper.DAYS_DELAY_UNITS:
                return getNextCheckDate(delay, Calendar.DATE);
            case TicketEscalationHelper.WORKDAYS_DELAY_UNITS:
                return getNextCheckDateForWorkDays(delay);
            default:
                throwException("Unsupported ticket escalation delay units: " + delayUnits);
                return null;
        }
    }

    //
    // Check ticket and ticket escalation.
    //
    private boolean equals(LogonSession ls, Object entityJEO, TicketEscalationObject escalation) 
        throws EQLException {
        Long ticketId = getTicketID(entityJEO);
        Long escalationId = escalation.getQw_escalationid();
        JEOManagerLocal jeoManager = getJEOManagerLocal();

        // Check for equal statuses.
        Integer ticketStatus = getTicketStatus(entityJEO);
        if(ticketStatus == null) {
            throw new NullPointerException("Field 'STATUS' is NULL. Ticket #" + ticketId);
        }
        List<EscStatusFieldObjectHandler> escStatusHandlers =
                EscStatusFieldObjectHandler.selectByEscalationId(jeoManager, ls, escalationId);
        if(escStatusHandlers != null) {
            boolean returned = false;
            for(EscStatusFieldObjectHandler escStatusFieldObjectHandler : escStatusHandlers) {
                EscStatusFieldObject escStatusFieldObject =
                        (EscStatusFieldObject) escStatusFieldObjectHandler.getJEObject();
                if(escStatusFieldObject.getQw_status().intValue() == ticketStatus) {
                    returned = true;
                    break;
                }
            }
            if(!returned) {
                return false;
            }
        }
        
        // Check for equal priorities.
        Integer ticketPriority = getTicketPriority(entityJEO);
        if(ticketPriority == null) {
            throw new NullPointerException("Field 'PRIORITY' is NULL. Ticket #" + ticketId);
        }
        List<EscPriorityFieldObjectHandler> escPriorityHandlers = 
                EscPriorityFieldObjectHandler.selectByEscalationId(jeoManager, ls, escalationId);
        if(escPriorityHandlers != null) {
            boolean returned = false;
            for(EscPriorityFieldObjectHandler escPriorityFieldObjectHandler : escPriorityHandlers) {
                EscPriorityFieldObject escPriorityFieldObject =
                        (EscPriorityFieldObject) escPriorityFieldObjectHandler.getJEObject();
                if(escPriorityFieldObject.getQw_priority().intValue() == ticketPriority) {
                    returned = true;
                    break;
                }
            }
            if(!returned) {
                return false;
            }
        }
        
        // Check for equals organizations(customers).
        if(!checkTicketOrgCustomer(ls, entityJEO, escalation.getQw_organizationid())){
            return false;
        }
        
        // Apply product filter.
        if(!checkTicketProduct(ls, entityJEO, escalation.getQw_productid(), escalation.getQw_productfilter())) {
            return false;
        }
        // Return true.
        return true;
    }

    protected boolean checkTicketOrgCustomer(LogonSession ls, Object entityJEO, Long escOrgId)
            throws EQLException {
        if(escOrgId == null) 
            return true;
        TicketObject ticket = (TicketObject) entityJEO;          
        Long ticketCustomer = ticket.getQw_customerid();
        boolean isIntCustomer = false;
        if(ticketCustomer == null) {
            ticketCustomer = ticket.getQw_employeeid();
            isIntCustomer = true;
        }
        Long ticketOrg = null;
        EQLManagerLocal eqlManager = getEQLManagerLocal();
            if(!isIntCustomer) {
                ticketOrg = CustomerObjectHandler.selectOrgByID(eqlManager, ls,
                        ticketCustomer);
            } else {
            ticketOrg = EmployeeObjectHandler.selectOrgByID(eqlManager, ls,
                    ticketCustomer);
            }
        if( ticketOrg == null )
            return false;
        else
            if( escOrgId.longValue() != ticketOrg.longValue() ) 
                return false;
        
        return true;
    }
    
    //
    // Checks ticket product.
    //
    protected boolean checkTicketProduct(LogonSession ls, Object entityJEO, Long escProduct, String filter)
            throws EQLException {
        Long ticketProduct = ((TicketObject) entityJEO).getQw_productid();
        // Check Ids.
        if(escProduct != null) {
            return escProduct.equals(ticketProduct);
        }
        // Check filters.
        if(filter == null) {
            // ..skip checking
            return true;
        }

        // check 'product' name by template
        ReqEntity reqEntity = new ReqEntity();
        reqEntity.setName(PRODUCT_ENTITY);

        Req req = new Req();
        req.setReqEntity(reqEntity);

        // .. add first condirion = id
        ReqFilters reqFilters = new ReqFilters();
        ReqFilter reqFilter = new ReqFilter();
        reqFilter.setEntity(PRODUCT_ENTITY);
        reqFilter.setName(PRODUCT_EFIELD_ID);
        reqFilter.setReqFilterValue(new String[]{String.valueOf(ticketProduct)});
        ReqFiltersTypeItem reqFiltersTypeItem = new ReqFiltersTypeItem();
        reqFiltersTypeItem.setReqFilter(reqFilter);
        reqFilters.addReqFiltersTypeItem(reqFiltersTypeItem);

        // .. add second condition like 'filter'
        reqFilter = new ReqFilter();
        reqFilter.setEntity(PRODUCT_ENTITY);
        reqFilter.setName(PRODUCT_EFIELD_NAME);
        reqFilter.setReqFilterValue(new String[]{filter});
        reqFiltersTypeItem = new ReqFiltersTypeItem();
        reqFiltersTypeItem.setReqFilter(reqFilter);
        reqFilters.addReqFiltersTypeItem(reqFiltersTypeItem);

        Reqs reqs = new Reqs();
        reqs.setReq(req);
        reqs.setReqFilters(reqFilters);
        reqs.setDoheader(Boolean.FALSE);
        reqs.setGetrequest(Boolean.FALSE);
        reqs.setDocount(Boolean.TRUE);

        // .. call GetRecords EJB
        GetRecordsLocal local = (GetRecordsLocal) getLocalObject(
                JNDINames.GetRecords, GetRecordsLocalHome.class);

        GetRecordsRes grRes = local.process(reqs, ls);
        Ress ress = grRes.getRess();

        if(getLogger().isInfoEnabled()) {
            INFO("Check product by the filter '" + filter + "' and pkey: "
                    + ticketProduct + ". Run GetRecords. Got count: " + ress.getCount());
        }

        return ress.getCount() > 0;
    }

    //
    // Checks escalation fireif.
    //
    protected boolean checkFireif(Object entityJEO,
                                TicketEscalationObject escObj,
                                TicketEsclEventObject eventObj) {
        TicketObject ticketObject = (TicketObject) entityJEO;  
        boolean continueEscalation = false;
        int fireif = escObj.getQw_fireif();
        switch(fireif) {
            case TicketEscalationHelper.NOT_CLOSED_FIREIF:
                // If ticket has status 'CLOSED' - break escalation
                if(ticketObject.getQw_status() != TicketHelper
                        .CLOSED_STATUS) {
                    // ..failed - continue
                    continueEscalation = true;
                }
                break;
            case TicketEscalationHelper.NOT_ASSIGNED_FIREIF:
                // If ticket has not status 'NEW' - break escalation
                if(ticketObject.getQw_status() == TicketHelper
                        .NEW_STATUS) {
                    // ..failed - continue
                    continueEscalation = true;
                }
                break;
            case TicketEscalationHelper.NOT_UPDATED_FIREIF:
                // If ticket's modified date is greater than event's - break
                // escalation
                Date eventDatemodified = eventObj.getQw_datemodified();
                Date ticketDatemodified = ticketObject.getQw_datemodified();
                if(eventDatemodified != null
                        && ticketDatemodified != null
                        && ticketDatemodified.getTime() <= eventDatemodified
                        .getTime()) {
                    // ..failed - continue
                    continueEscalation = true;
                }
                break;
            default:
                throwException("Unsupported escalation 'FireIf': " + fireif);
        }
        return continueEscalation;
    }

    //
    // Loads the employee user by ID.
    //
    protected User loadEmployee(LogonSession ls, Long employeeID) {
        try {
            if(employeeID != null) {
                return ApplicationHelper.loadEmployee(ls, employeeID);
            }
        } catch (EQLException ex) {
            throwException(ex);
        }
        return null;
    }

    
    //
    // Ticket entity loader.
    //
    protected Entity loadTicketEntity() {
        return getEntityViewConfigManagerLocal().getEntityViewConfig(
                TicketObjectHandler.ENTITY);
    }

    protected void infoMsg(Object entityJEO){
        TicketObject ticketObj = (TicketObject) entityJEO;
        Long ticketCustomerId = ticketObj.getQw_customerid();
        if(ticketCustomerId == null) {
            ticketCustomerId = ticketObj.getQw_employeeid();
        }
        INFO("Creating escalation events for the ticket:" + "\n\t ID = "
                + ticketObj.getQw_ticketid() + "\n\t priority = "
                + ticketObj.getQw_priority() + "\n\t status = "
                + ticketObj.getQw_status() + "\n\t customer ID = "
                + ticketCustomerId);
    }
    
    protected Long getTicketID(Object entityJEO){
        return ((TicketObject) entityJEO).getQw_ticketid();
    }
    
    protected Date getTicketDateModified(Object entityJEO){
        return ((TicketObject) entityJEO).getQw_datemodified();
    }
    
    protected Integer getTicketStatus(Object entityJEO){
        return ((TicketObject) entityJEO).getQw_status();
    }

    protected Integer getTicketPriority(Object entityJEO){
        return ((TicketObject) entityJEO).getQw_priority();
    }

    protected int getNotUpdatedFireIf(){
        return TicketEscalationHelper.NOT_UPDATED_FIREIF;
    }
    
    protected List getEscalationList(JEOManagerLocal jeoManager, LogonSession ls) throws EQLException {
        return TicketEscalationObjectHandler.selectAll( jeoManager, ls);
    }
    
    protected TicketEscalationObjectHandler getTicketEscalationObjectHandler(
                JEOManagerLocal jeoManager, LogonSession ls, Long escId) throws EQLException{
        if(escId == null)
            return null;
        else
            return (TicketEscalationObjectHandler)
                        TicketEscalationObjectHandler.selectByPkey(jeoManager, ls, escId.longValue());
    }

    protected JEObject getJEObjectById(
            JEOManagerLocal jeoManager, LogonSession ls, Long ticketId) throws EQLException{
        TicketObjectHandler ticketHnd = (TicketObjectHandler) 
                TicketObjectHandler.selectByID(jeoManager, ls, ticketId);
        if(ticketHnd == null)
            return null;
        else
            return ticketHnd.getJEObject();
    }
    
    
}
