/*
 * Copyright (C) 2003-2016 eXo Platform SAS.
 *
 * 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 org.exoplatform.cs.dao;

import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.exoplatform.commons.persistence.impl.GenericDAOJPAImpl;
import org.exoplatform.cs.entity.TypeEntity;

/**
 * Created by The eXo Platform SAS
 * 
 * @author boubaker.khanfir@exoplatform.com
 * @since Apr 27, 2016
 */
public class TypeDAO extends GenericDAOJPAImpl<TypeEntity, Long> {
  private static final Logger LOG = LoggerFactory.getLogger(TypeDAO.class);

  public TypeEntity getTypeByName(String name) {
    if (StringUtils.isBlank(name)) {
      return null;
    }
    try {
      return getEntityManager().createNamedQuery("typeEntity.getTypeByName", TypeEntity.class)
                               .setParameter("name", name)
                               .getSingleResult();
    } catch (NoResultException e) {
      return null;
    } catch (NonUniqueResultException e) {
      // Impossible case, name is unique in DB
      LOG.error("Impossible case, Type with name " + name + " is not unique", e);
      return null;
    } catch (Exception e) {
      LOG.error("An uknown error was returned", e);
      return null;
    }
  }

  public <T extends TypeEntity> List<T> getTypeObjects(Class<T> classEntity) {
    if (classEntity == null) {
      return null;
    }
    try {
      return (List<T>) getEntityManager().createQuery("from CS" + classEntity.getSimpleName() + " where other = false", classEntity).getResultList();
    } catch (NoResultException e) {
      return null;
    } catch (Exception e) {
      LOG.error("An uknown error occured", e);
      return null;
    }
  }
}
