/*
 * 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.server.app.rpc;

import com.queplix.core.client.app.rpc.DisplayableException;
import com.queplix.core.client.app.vo.EmailComposeRequestObject;
import com.queplix.core.integrator.IntegratorHelper;
import com.queplix.core.integrator.security.LogonSession;
import com.queplix.core.integrator.security.WebLoginManager;
import com.queplix.core.modules.eql.error.EQLException;
import com.queplix.core.modules.inbox.InboxHelper;
import com.queplix.core.modules.inbox.InboxMessage;
import com.queplix.core.modules.jeo.ejb.JEOManagerLocal;
import com.queplix.core.modules.jeo.ejb.JEOManagerLocalHome;
import com.queplix.core.modules.jeo.gen.AccountObject;
import com.queplix.core.modules.jeo.gen.AccountObjectHandler;
import com.queplix.core.modules.jeo.gen.InboxObject;
import com.queplix.core.modules.jeo.gen.InboxObjectHandler;
import com.queplix.core.modules.mail.MailAddress;
import com.queplix.core.utils.JNDINames;
import com.queplix.core.utils.StringHelper;
import com.queplix.core.utils.cache.CacheObjectManager;
import com.queplix.core.utils.log.AbstractLogger;
import com.queplix.core.utils.log.Log;
import com.queplix.qwoss.inbox.ejb.InboxManagerLocal;
import com.queplix.qwoss.inbox.ejb.InboxManagerLocalHome;
import com.queplix.qwoss.utils.CustomJNDINames;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

public class InboxRPCHelper {
    // Logger reference.
    private static final AbstractLogger logger = Log.getLog(
            InboxRPCHelper.class);

    public static boolean sendReply(EmailComposeRequestObject request,
                                    int objectType, long objectId,
                                    HttpServletRequest httpRequest)
            throws DisplayableException, EQLException {
        LogonSession ls = WebLoginManager.getLogonSession(httpRequest);

        MailAddress[] to = MailAddress.parse(request.getTo());
        MailAddress from;
        String fromAddr = request.getFrom();
        if(!StringHelper.isEmpty(fromAddr)) {
            from = new MailAddress(fromAddr);
        } else {
            String defaultSender = InboxHelper.getDefSender(ls);
            from = new MailAddress(defaultSender);
        }

        InboxMessage message = new InboxMessage(to, from, request.getSubject(),
                request.getBody());

        String ccAddr = request.getCc();
        if(!StringHelper.isEmpty(ccAddr)) {
            message.setCc(MailAddress.parse(ccAddr));
        }

        message.setProcessId(request.getProcess_id());
        message.setObjectInfo(new Long(objectId), new Integer(objectType));
        InboxManagerLocal inboxLocal = getInboxManagerLocal();

        //Properties
        try {
            inboxLocal.sendReply(ls, message, null);
        } catch (Exception ex) {
            IntegratorHelper.reThrowException(ex);
            return false;
        }

        // Set task status to "Interrupted"

        return true;
    }

    public static Boolean deleteInbox(Collection<Long> inboxPkeys,
                                      HttpServletRequest request)
            throws EQLException {
        LogonSession ls = WebLoginManager.getLogonSession(request);
        JEOManagerLocal jeoManager = (JEOManagerLocal)
                new CacheObjectManager().getLocalObject(JNDINames.JEOManager,
                        JEOManagerLocalHome.class);
        for(Long inboxPkey : inboxPkeys) {
            logger.INFO("Set delete flag for inbox pkey #" + inboxPkey);
            InboxObjectHandler hnd = (InboxObjectHandler) InboxObjectHandler
                    .selectByPkey(jeoManager, ls, inboxPkey);

            if(hnd != null) {
                InboxObject inboxObject = (InboxObject) hnd.getJEObject();
                inboxObject.setDelete_flag(InboxHelper.DELETE_FLAG);
                jeoManager.commit(hnd);
            } else {
                return Boolean.FALSE;
            }
        }
        return Boolean.TRUE;
    }

    public static String getAccountReplyEmail(Long accuntId,
                                              HttpServletRequest httpRequest)
            throws DisplayableException, EQLException {
        LogonSession ls = WebLoginManager.getLogonSession(httpRequest);
        JEOManagerLocal jeoManager = (JEOManagerLocal)
                new CacheObjectManager().getLocalObject(JNDINames.JEOManager,
                        JEOManagerLocalHome.class);
        logger.INFO("getAccountReplyEmail : Account # " + accuntId);
        AccountObject accObj = AccountObjectHandler.selectByPkey(jeoManager, ls,
                accuntId.longValue());
        return accObj.getReply_email();
    }

    protected static InboxManagerLocal getInboxManagerLocal() {
        CacheObjectManager com = new CacheObjectManager();
        return (InboxManagerLocal) com.getLocalObject(
                CustomJNDINames.InboxManager,
                InboxManagerLocalHome.class);
    }

}