/*
 * 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.update;

import com.queplix.core.integrator.security.LogonSession;
import com.queplix.core.integrator.security.User;
import com.queplix.core.modules.eql.error.EQLException;
import com.queplix.core.modules.eql.update.EntityUpdate;
import com.queplix.core.modules.jeo.JEObjectHandler;
import com.queplix.core.modules.jeo.ejb.JEOManagerLocal;
import com.queplix.core.modules.jeo.ejb.JEOManagerLocalHome;
import com.queplix.core.utils.DateHelper;
import com.queplix.core.utils.JNDINames;
import com.queplix.qwoss.gen.ShortTicketObject;
import com.queplix.qwoss.gen.ShortTicketObjectHandler;
import com.queplix.qwoss.gen.SolutionObject;
import com.queplix.qwoss.gen.SolutionObjectHandler;
import com.queplix.qwoss.gen.WorkflowObject;
import com.queplix.qwoss.gen.WorkflowObjectHandler;
import com.queplix.qwoss.utils.SolutionHelper;
import com.queplix.qwoss.utils.WorkflowHelper;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * Description.
 *
 * @author Sergei Savchuk
 */
public class SolutionUpdate extends EntityUpdate {

    public int beforeUpdate() throws EQLException {
        // Initialization.
        JEOManagerLocal jeoManager = (JEOManagerLocal)
                getCOM().getLocalObject(JNDINames.JEOManager,
                        JEOManagerLocalHome.class);
        LogonSession ls = getEUO().getSession().getLogonSession();
        User user = ls.getUser();

        // Get current ticket record.
        JEObjectHandler hnd = getJEOHandler(jeoManager,
                SolutionObjectHandler.class);
        SolutionObject solObj = (SolutionObject) hnd.getJEObject();
        Date nowDate = DateHelper.getNowDate();
        long userId = user.getUserID();

        if(isNew()) {
            if(solObj.getQw_solutionstatus().intValue() != SolutionHelper
                    .DRAFT_STATUS) {
                throw new EQLException(
                        "The status for new solution can be 'Draft' only!");
            }
        } else {
            int newStatus = solObj.getQw_solutionstatus().intValue();
            if(solObj.isChangedQw_solutionstatus()) {
                String textNewStatus = solObj.textQw_solutionstatus();
                int oldStatus = solObj.oldQw_solutionstatus().intValue();
                List<WorkflowObjectHandler> workflows = WorkflowObjectHandler
                        .selectByObjAndStatusTo(jeoManager, ls,
                                WorkflowHelper.SOLUTION_TYPE, newStatus);

                if(workflows == null) {
                    throw new EQLException(
                            "You don't have privileges to set solution to the '"
                                    + textNewStatus + "' status!");
                }

                if(!checkWorkflow(workflows, oldStatus, user.getRolesIDs())) {
                    throw new EQLException(
                            "You don't have privileges to set solution to the '"
                                    + textNewStatus + "' status!");
                }

                switch(newStatus) {
                    case SolutionHelper.REVIEWED_STATUS:
                        solObj.setQw_datereviewed(nowDate);
                        solObj.setQw_reviewer(userId);
                        break;
                    case SolutionHelper.PUBLISHED_STATUS:
                        solObj.setQw_datepublished(nowDate);
                        solObj.setQw_publisher(userId);
                        break;
                    case SolutionHelper.RETIRED_STATUS:
                        break;
                }
            }
            if(solObj.isChangedQw_dateexpiration()
                    && newStatus != SolutionHelper.PUBLISHED_STATUS) {
                throw new EQLException(
                        "You may change expiration date only for 'Published' solutions!");
            }
        }
        solObj.setQw_modifiedby(userId);
        solObj.setQw_lastmodified(nowDate);
        return CONTINUE;
    }

    private boolean checkWorkflow(List<WorkflowObjectHandler> workflows,
                                  int oldStatus, Set<Long> roles)
            throws EQLException {
        for(WorkflowObjectHandler workflowHnd : workflows) {
            WorkflowObject workflow = (WorkflowObject) workflowHnd
                    .getJEObject();
            int statusFrom = workflow.getQw_statusfrom();
            long roleId = workflow.getQw_roleid().longValue();
            if(statusFrom == oldStatus && roles.contains(new Long(roleId))) {
                return true;
            }
        }
        return false;
    }

    public void afterUpdate() throws EQLException {
        // New Solution
        if(isNew()) {
            // Initialization.
            INFO("Sync script started ...");
            JEOManagerLocal jeoManager = (JEOManagerLocal)
                    getCOM().getLocalObject(JNDINames.JEOManager,
                            JEOManagerLocalHome.class);
            LogonSession ls = getEUO().getSession().getLogonSession();

            Long originTicketId = getCell(SolutionHelper.ORIGIN_TICKET_FIELD)
                    .getLong();
            Long solutionId = getCell(SolutionHelper.SOLUTION_ID_FIELD)
                    .getLong();
            if(originTicketId != null && originTicketId.longValue() > 0) {
                JEObjectHandler ticketHnd = ShortTicketObjectHandler.selectByID(
                        jeoManager, ls, originTicketId.longValue());
                if(ticketHnd
                        != null) { //there is ticket, thus update qw_solution field
                    INFO("Ticket # " + originTicketId + " was found.");
                    ShortTicketObject ticketObj = (ShortTicketObject) ticketHnd
                            .getJEObject();
                    ticketObj.setQw_solution(solutionId);
                    jeoManager.commit(ticketHnd);
                    INFO("Solution # " + solutionId
                            + " was assigned to Ticket # " + originTicketId
                            + ".");
                } else {
                    INFO("Ticket # " + originTicketId + " does not exist.");
                }
            }
        }
    }

}
