/*
 * 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.Calendar;
import java.util.List;


import javax.persistence.TemporalType;
import org.exoplatform.cs.dto.IssueType;
import org.exoplatform.cs.entity.SpaceEntity;
import org.exoplatform.cs.service.CSConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

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

  public List<TopicEntity> getTopicsBySpace(String spaceGroupId, String selectedStatus) {
    try {
      if(selectedStatus != null && !selectedStatus.isEmpty()){
        return getEntityManager().createNamedQuery("topicEntity.getTopicsBySpaceAnsStatus", TopicEntity.class).
            setParameter("status",selectedStatus).
            setParameter("spaceGroupID", spaceGroupId).getResultList();
      } else {
        return getEntityManager().createNamedQuery("topicEntity.getTopicsBySpace", TopicEntity.class).
            setParameter("spaceGroupID", spaceGroupId).getResultList();
      }
    } catch (Exception e) {
      LOG.error("Exception while attempting to get topics of space '" + spaceGroupId + "'.", e);
      throw e;
    }

  }

  /**
   * Fetches all topics by assignee
   *
   * @param assignee
   * The assignee ID
   * @param allTickets true if we need to get closed tickets, false otherwise
   * @param selectedStatus
   * @return List of Topic entities
   */
  public List<TopicEntity> getTopicsByAssignee(String assignee, boolean allTickets, String selectedStatus) {
    try {
      if(allTickets) {
        if(selectedStatus != null && ! selectedStatus.isEmpty()){
          return getEntityManager().createNamedQuery("topicEntity.getTopicsByAssigneeAndStatus", TopicEntity.class)
              .setParameter("assignee", assignee).setParameter("status",selectedStatus).getResultList();
        } else {
          return getEntityManager().createNamedQuery("topicEntity.getTopicsByAssignee", TopicEntity.class)
              .setParameter("assignee", assignee).getResultList();
        }
      } else {
        if(selectedStatus != null && ! selectedStatus.isEmpty()){
          return getEntityManager().createNamedQuery("topicEntity.getTopicsByAssigneeAndStatus", TopicEntity.class)
              .setParameter("assignee", assignee)
              .setParameter("status", selectedStatus)
              .getResultList();
        }else {
          return getEntityManager().createNamedQuery("topicEntity.getOpenTopicsByAssignee", TopicEntity.class)
              .setParameter("assignee", assignee)
              .setParameter("status", CSConstants.STATUS_CLOSED).getResultList();
        }
      }
    } catch (Exception e) {
      LOG.error("Exception while attempting to get topics by assignee '" + assignee + "'.", e);
      throw e;
    }

  }

  /**
   * Fetches all topics by assignee
   * @param assignee The assignee ID
   * @param selectedSpace the space to retrieve tickets from
   * @param allTickets true if we need to get closed tickets, false otherwise
   * @return List of Topic entities
   */
  public List<TopicEntity> getTopicsByAssignee(String assignee, String selectedSpace, boolean allTickets, String selectedStatus) {
    try {
      if(allTickets) {
        if(selectedStatus != null && ! selectedStatus.isEmpty()){
          return getEntityManager().createNamedQuery("topicEntity.getTopicsBySpaceAndAssigneeAndStatus", TopicEntity.class)
              .setParameter("assignee", assignee).setParameter("status",selectedStatus).setParameter("spaceGroupID", selectedSpace).getResultList();
        } else {
          return getEntityManager().createNamedQuery("topicEntity.getTopicsBySpaceAndAssignee", TopicEntity.class)
              .setParameter("assignee", assignee).setParameter("spaceGroupID", selectedSpace).getResultList();
        }
      } else {
        if(selectedStatus != null && ! selectedStatus.isEmpty()){
          return getEntityManager().createNamedQuery("topicEntity.getTopicsBySpaceAndAssigneeAndStatus", TopicEntity.class)
              .setParameter("assignee", assignee).setParameter("status",selectedStatus).setParameter("spaceGroupID", selectedSpace).getResultList();
        } else {
          return getEntityManager().createNamedQuery("topicEntity.getOpenTopicsByAssigneeAndSpace", TopicEntity.class)
              .setParameter("assignee", assignee)
              .setParameter("spaceGroupID", selectedSpace)
              .setParameter("status", CSConstants.STATUS_CLOSED).getResultList();
        }
      }
    } catch (Exception e) {
      LOG.error("Exception while attempting to get topics by assignee '" + assignee + "'.", e);
      throw e;
    }

  }

  public List<TopicEntity> getOpenTickets() {
    return getEntityManager().createNamedQuery("topicEntity.getOpenTopics", TopicEntity.class)
        .setParameter("status", CSConstants.STATUS_CLOSED).getResultList();
  }

  public List<TopicEntity> findUpdatedBetween(Calendar fromDate, Calendar toDate) {
    return getEntityManager().createNamedQuery(
        "topicEntity.findUpdatedTopics", TopicEntity.class)
        .setParameter("from", fromDate, TemporalType.TIMESTAMP).
            setParameter("to", toDate, TemporalType.TIMESTAMP).getResultList();
  }

  public Long countTickets(SpaceEntity space, IssueType type) {
    return getEntityManager().createNamedQuery("topicEntity.countTickets", Long.class)
        .setParameter("type", type).setParameter("space", space).getSingleResult();
  }
  @Deprecated
  public List<TopicEntity> getEmptyTitleOrCreationDate () {
    return getEntityManager().createNamedQuery("topicEntity.findEmptyTitleAndCreationDateTopics",
                                               TopicEntity.class).setMaxResults(50).getResultList();
  }

  public List<TopicEntity> getWithEmptyTicketID() {
    return getEntityManager().createNamedQuery("topicEntity.findEmptyTicketID",
                                               TopicEntity.class).setMaxResults(50).getResultList();
  }

  public List<TopicEntity> getOpenTicketsBySpace(String selectedSpace, String selectedStatus) {
      if(selectedStatus != null && !selectedStatus.isEmpty()) {
          return getEntityManager().createNamedQuery("topicEntity.findOpenTicketsBySpaceAndStatus",
                  TopicEntity.class).setParameter("spaceGroupID", selectedSpace)
                  .setParameter("status", selectedStatus)
                  .setParameter("closedStatus", CSConstants.STATUS_CLOSED).getResultList();
      } else {
          return getEntityManager().createNamedQuery("topicEntity.findOpenTicketsBySpace",
                  TopicEntity.class).setParameter("spaceGroupID", selectedSpace)
                  .setParameter("closedStatus", CSConstants.STATUS_CLOSED).getResultList();
      }
  }

  public TopicEntity findByTicketId(String ticketId) {
    return getEntityManager().createNamedQuery("topicEntity.findTicketByTicketId",
                                               TopicEntity.class).setParameter("ticketId",ticketId).getSingleResult();
  }

  public List<TopicEntity> findByStatus(String selectedStatus) {
    return getEntityManager().createNamedQuery("topicEntity.findAllTicketByStatus",
                                               TopicEntity.class).setParameter("status",selectedStatus).getResultList();
  }

  public List<TopicEntity> getOpenTicketsByStatus(String selectedStatus) {
      if(selectedStatus != null && !selectedStatus.isEmpty()) {
          return getEntityManager().createNamedQuery("topicEntity.findOpenTicketsByStatus", TopicEntity.class)
                  .setParameter("status", selectedStatus)
                  .setParameter("closedStatus", CSConstants.STATUS_CLOSED).getResultList();
      } else {
          return getEntityManager().createNamedQuery("topicEntity.getOpenTopics", TopicEntity.class)
                  .setParameter("status", CSConstants.STATUS_CLOSED).getResultList();

      }
  }
}
