/*
 * Copyright (C) 2005 - 2011 Jaspersoft Corporation. All rights reserved.
 * http://www.jaspersoft.com.
 *
 * Unless you have purchased  a commercial license agreement from Jaspersoft,
 * the following license terms  apply:
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License  as
 * published by the Free Software Foundation, either version 3 of  the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero  General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public  License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package com.jaspersoft.jasperserver.search.filter;

import com.jaspersoft.jasperserver.api.search.SearchCriteria;
import com.jaspersoft.jasperserver.api.common.domain.ExecutionContext;
import com.jaspersoft.jasperserver.api.metadata.user.domain.User;
import com.jaspersoft.jasperserver.api.metadata.user.service.TenantService;
import com.jaspersoft.jasperserver.search.common.SearchAttributes;
import org.hibernate.criterion.*;

/**
 * Access type filter.
 * 
 * @author Stas Chubar
 * @version $Id$
 */
public class AccessTypeFilter extends BaseSearchFilter {

    public void applyRestrictions(String type, ExecutionContext context, SearchCriteria criteria) {
        SearchAttributes searchAttributes = getSearchAttributes(context);

        User user = null;

        if (context.getAttributes() != null) {
            for(Object o : context.getAttributes()) {
                if (o instanceof User) {
                    user = (User) o;
                }
            }
        }

        if (user != null && searchAttributes != null && searchAttributes.getState() != null) {
            String accessFilter = searchAttributes.getState().getCustomFiltersMap().get("accessTypeFilter");
            if (accessFilter != null && !accessFilter.equals("accessTypeFilter-all")) {
                
                String alias = criteria.getAlias("accessEvents", "ae");
                criteria.add(Restrictions.eq(alias + ".updating", accessFilter.equals("accessTypeFilter-changedByMe")));

                String userAlias = criteria.getAlias(alias + ".user", "u");
                criteria.add(Restrictions.eq(userAlias + ".username", user.getUsername()));

                String tenantId = (user.getTenantId() == null) ? TenantService.ORGANIZATIONS : user.getTenantId();    
                String tenantAlias = criteria.getAlias(userAlias + ".tenant", "t");
                criteria.add(Restrictions.eq(tenantAlias + ".tenantId", tenantId));
            }
        }
    }
}