/*
 * 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.core.integrator.security;

import com.queplix.core.modules.eql.ejb.EQLManagerLocal;
import com.queplix.core.modules.eql.ejb.EQLManagerLocalHome;
import com.queplix.core.modules.eql.error.EQLException;
import com.queplix.core.modules.jeo.ejb.JEOManagerLocal;
import com.queplix.core.modules.jeo.ejb.JEOManagerLocalHome;
import com.queplix.core.modules.jeo.gen.UserGroupObjectHandler;
import com.queplix.core.modules.jeo.gen.UserObject;
import com.queplix.core.modules.jeo.gen.UserObjectHandler;
import com.queplix.core.modules.jeo.gen.WorkgroupObject;
import com.queplix.core.modules.jeo.gen.WorkgroupObjectHandler;
import com.queplix.core.utils.JNDINames;
import com.queplix.core.utils.SystemHelper;
import com.queplix.core.utils.cache.CacheObjectManager;
import com.queplix.core.utils.log.AbstractLogger;
import com.queplix.core.utils.log.Log;

import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Store some help functions.
 *
 * @author Sergey Kozmin
 * @since 17.01.2007
 */
public class SecurityHelper {

    // Logger.
    private static AbstractLogger logger = Log.getLog(SecurityHelper.class);
    // Cache object manager
    private static final CacheObjectManager com = new CacheObjectManager();

    /**
     * Retrieve {@link java.util.TimeZone} object for the given timezone, or if it's not possible returns default system time zone.
     *
     * @param timezoneID requested time zone id
     * @return {@link java.util.TimeZone} object for the given timezone.
     * @see com.queplix.core.utils.SystemHelper#DEFAULT_TIMEZONE
     */
    public static TimeZone getJavaTimezone(String timezoneID) {
        TimeZone javaTz = null;

        if(timezoneID != null) {
            javaTz = TimeZone.getTimeZone(timezoneID);
        }

        if(javaTz == null) {
            javaTz = SystemHelper.DEFAULT_TIMEZONE;
        }
        return javaTz;
    }

    /**
     * Constract locale for the given country id and lang id. If one of the argument is null return defaul locale.
     *
     * @param countryID contry id
     * @param langID    lang id
     * @return {@link java.util.Locale} object for the given country and language.
     */
    public static Locale getJavaLocale(String countryID, String langID) {
        Locale locale = null;

        if(countryID != null && langID != null) {
            locale = new Locale(langID, countryID);
        }

        if(locale == null) {
            locale = SystemHelper.DEFAULT_LOCALE;
        }

        return locale;
    }

    public static List loadUsers(LogonSession ls, WorkGroup group) {
        return loadUsers(ls, group, null);
    }

    /*
     * (non-Javadoc)
     *
     * @see EmployeeUserDAO#loadUsers
     */
    public static List loadUsers(LogonSession ls, WorkGroup group,
                                 Integer tier) {
        if(logger.getLogger().isInfoEnabled()) {
            logger.INFO("Try to load employees for group '" + group
                    + "' and tier '" + tier + "'");
        }
        List users = null;
        // Initialization.
        JEOManagerLocal jeoManager = getJEOManagerLocal();
        try {
            if(tier == null) {
                users = UserObjectHandler.selectByWorkgroupID(jeoManager, ls,
                        new Long(group.getGroupID()));
            } else {
                users = UserObjectHandler.selectByWorkgroupIDAndTier(jeoManager,
                        ls, new Long(group.getGroupID()), tier);
            }
        } catch (EQLException e) {
            return null;
        }
        if(logger.getLogger().isInfoEnabled()) {
            logger.INFO("Got " + users.size() + " employee(s)");
        }
        return (users.size() == 0) ? null:users;
    }

    public static User loadNotifiedUser(LogonSession ls, Long userID)
        throws EQLException {
        if(userID == null) {
            return null;
        }
        logger.DEBUG("Try to get data for " + userID + " user");
        User user;
        JEOManagerLocal jeoManager = getJEOManagerLocal();
        UserObject userObj = UserObjectHandler.selectObjectByID(jeoManager, ls,
                userID);
        user = new User();
        user.setUserID(userObj.getPkey());
        user.setUserType(userObj.getUser_type());
        user.setLoginName(userObj.getLoginname());
        user.setFullName(userObj.getFullname());
        user.setEmail(userObj.getEmail());
        user.setPasswordDigest(userObj.getPassword());
        logger.DEBUG("Got user for " + userID + " : " + user.getLoginName());
        return user;
    }
    
    public static WorkGroup loadGroup(LogonSession ls, Long groupID)
            throws EQLException {
        if(groupID == null) {
            return null;
        }
        if(logger.getLogger().isDebugEnabled()) {
            logger.DEBUG("Try to load group: " + groupID);
        }
        WorkgroupObject wgroupObj = WorkgroupObjectHandler.selectByID(
                getJEOManagerLocal(), ls, groupID);
        if(wgroupObj == null) {
            return null;
        }
        if(logger.getLogger().isDebugEnabled()) {
            logger.DEBUG("Got group '" + wgroupObj.getName() + "'");
        }
        Long wgNotifyMethod = wgroupObj.getNotifymethod();
        if(wgNotifyMethod != null) {
            return new WorkGroup(wgroupObj.getPkey().longValue(),
                    wgroupObj.getName(), wgroupObj.getNotificationaddr(),
                    wgNotifyMethod.intValue());
        } else {
            return new WorkGroup(wgroupObj.getPkey().longValue(),
                    wgroupObj.getName(), wgroupObj.getNotificationaddr());
        }
    }

    public static Integer loadUserGroupNotifyMethod(LogonSession ls, User user,
                                                    Long groupID) {
        if(user == null || groupID == null) {
            return null;
        }
        if(logger.getLogger().isDebugEnabled()) {
            logger.DEBUG("Try to load user group notify method: user # "
                    + user.getUserID() + " group # " + groupID);
        }
        long userID = user.getUserID();
        int userType = user.getUserType();
        Integer notifyMethod = null;

        try {
            notifyMethod = UserGroupObjectHandler.selectNotifyMethod(
                    getEQLManagerLocal(), ls, userID,
                    userType, groupID.longValue());
        } catch (EQLException e) {
            return null;
        }

        if(logger.getLogger().isDebugEnabled()) {
            logger.DEBUG("Got user group notify method: " + notifyMethod);
        }
        return notifyMethod;
    }

    private static JEOManagerLocal getJEOManagerLocal() {
        return (JEOManagerLocal) com.getLocalObject(JNDINames.JEOManager,
                JEOManagerLocalHome.class);
    }

    private static EQLManagerLocal getEQLManagerLocal() {
        return (EQLManagerLocal) com.getLocalObject(JNDINames.EQLManager,
                EQLManagerLocalHome.class);
    }


}
