<?php

  /**
   * Comments manager class
   *
   * @package activeCollab.modules.resources
   * @subpackage models
   */
  class Comments extends FwComments {

    /**
     * Find all project attachments
     *
     * @param Project $project
     * @param integer $min_state
     * @return DBResult
     */
    static function findForApiByProject(Project $project, $min_state = STATE_ARCHIVED) {
      $comments_table = TABLE_PREFIX . 'comments';

      if($project->getState() >= STATE_VISIBLE) {
        $map = Comments::findTypeIdMapOfPotentialParents($project, $min_state);

        if($map) {
          $conditions = array();

          foreach($map as $type => $ids) {
            $conditions[] = DB::prepare('(parent_type = ? AND parent_id IN (?))', array($type, $ids));
          } // if

          $conditions = implode(' OR ', $conditions);

          $result = DB::execute("SELECT id, type, parent_type, parent_id, body, body AS 'body_formatted', state, created_on, created_by_id, created_by_name, created_by_email FROM $comments_table WHERE ($conditions) AND state >= ?", $min_state);

          if($result) {
            $result->setCasting(array(
              'id' => DBResult::CAST_INT,
              'parent_id' => DBResult::CAST_INT,
              'state' => DBResult::CAST_INT,
              'body_formatted' => function($in) {
                return HTML::toRichText($in);
              },
              'created_by_id' => DBResult::CAST_INT,
            ));

            return $result;
          } // if
        } // if
      } // if

      return null;
    } // findForApiByProject

    /**
     * Find type ID map of potential comment parents in a given project
     *
     * @param Project $project
     * @param integer $min_state
     * @return array
     */
    static function findTypeIdMapOfPotentialParents(Project $project, $min_state = STATE_ARCHIVED) {
      $map = array();

      $rows = DB::execute('SELECT id, type FROM ' . TABLE_PREFIX . 'project_objects WHERE project_id = ? AND state >= ?', $project->getId(), $min_state);
      if($rows) {
        foreach($rows as $row) {
          if(array_key_exists($row['type'], $map)) {
            $map[$row['type']][] = (integer) $row['id'];
          } else {
            $map[$row['type']] = array((integer) $row['id']);
          } // if
        } // foreach
      } // if

      EventsManager::trigger('on_extend_project_items_type_id_map', array(&$project, $min_state, &$map));

      return count($map) ? $map : null;
    } // findTypeIdMapOfPotentialParents

  }