<?php

  /**
   * Shared object comments helper implementation
   * 
   * @package activeCollab.modules.system
   * @subpackage helpers
   */

  /**
   * Display shared object comments
   * 
   * @param array $params
   * @param Smarty $smarty
   * @return string
   */
  function smarty_function_shared_object_comments($params, &$smarty) {
    $object = array_required_var($params, 'object', true, 'ISharing');
    $user = array_var($params, 'user', null, true); // User is optional, since this helper can be used through public interface
    $object_as_comment = array_var($params, 'object_as_first_comment', false, true);
    $errors = array_var($params, 'errors', null, true);
    $comment_data = array_var($params, 'comment_data', array(), true);
    
    if (!($user instanceof User)) {
    	$user = new AnonymousUser('','anonymous@anonymous.com');
    } // if
    
    $result = HTML::openTag('div', $params);
    
    if($object->sharing()->supportsComments()) {
      if($object->sharing()->canComment($user)) {
        $template = $smarty->createTemplate(get_view_path('_shared_object_comment_form', 'shared_object', SYSTEM_MODULE));
        $template->assign(array(
          'object' => $object, 
          'user' => $user,
          'comment_data' => $comment_data,
          'attachments_supported' => $object->sharing()->getSharingProfile()->getAdditionalProperty('attachments_enabled'),
          'errors' => $errors
        ));
        
        $result .= $template->fetch();
      } // if
      
      $comments = $object->comments()->getPublic();
      
      if($comments || $object_as_comment) {
        $template = $smarty->createTemplate(get_view_path('_shared_object_comment', 'shared_object', SYSTEM_MODULE));
        
        if($comments) {
          foreach($comments as  $comment) {
            $template->assign(array(
              'created_by' => $comment->getCreatedBy(), 
              'created_on' => $comment->getCreatedOn(), 
              'updated_on' => $comment->getUpdatedOn(), 
              'body' => $comment->getBody(), 
              'attachments' => $comment->attachments()->getPublic(), 
            ));
            
            $result .= $template->fetch();
          } // foreach
        } // if
        
        if($object_as_comment) {
          $template->assign(array(
            'created_by' => $object->getCreatedBy(), 
            'created_on' => $object->getCreatedOn(), 
            'updated_on' => $object->getUpdatedOn(), 
            'body' => $object->getBody(), 
            'attachments' => $object->attachments()->getPublic(), 
          ));
          
          $result .= $template->fetch();
        } // if
      } else {
        $result .= '<p class="empty_page">' . lang('No comments yet') . '</p>';
      } // if
    } // if
    
    return $result . '</div>';
  } // smarty_function_shared_object_comments