<?php

  // Build on top of assets controller
  AngieApplication::useController('assets', FILES_MODULE);

  /**
   * Bookmarks controller
   *
   * @package activeCollab.modules.files
   * @subpackage controllers
   */
  class BookmarksController extends AssetsController {
    
    /**
     * Construct bookmarks controller
     *
     * @param Request $parent
     * @param mixed $context
     */
    function __construct(Request $parent, $context = null) {
      parent::__construct($parent, $context);
      
      if($this->getControllerName() == 'bookmarks') {
        $this->state_delegate = $this->__delegate('state', ENVIRONMENT_FRAMEWORK_INJECT_INTO, 'project_assets_bookmark');
        $this->comments_delegate = $this->__delegate('comments', COMMENTS_FRAMEWORK_INJECT_INTO, 'project_assets_bookmark');
        $this->subscriptions_delegate = $this->__delegate('subscriptions', SUBSCRIPTIONS_FRAMEWORK_INJECT_INTO, 'project_assets_bookmark');
				$this->reminders_delegate = $this->__delegate('reminders', REMINDERS_FRAMEWORK_INJECT_INTO, 'project_assets_bookmark');
				$this->sharing_settings_delegate = $this->__delegate('sharing_settings', SYSTEM_MODULE, 'project_assets_bookmark');
				$this->move_to_project_delegate = $this->__delegate('move_to_project', SYSTEM_MODULE, 'project_assets_bookmark');
      } // if
    } // __construct
    
    /**
     * Prepare controller
     */
    function __before() {
      parent::__before();
      
			if(!$this->active_asset || $this->active_asset->isNew()) {
        $this->active_asset = new Bookmark();
        $this->active_asset->setProject($this->active_project);
        
        $this->response->assign('active_asset', $this->active_asset);
      } else if ($this->active_asset->isLoaded() && !($this->active_asset instanceof Bookmark)) {
        $this->response->notFound();
      } // if
            
      if($this->state_delegate instanceof StateController) {
        $this->state_delegate->__setProperties(array(
          'active_object' => &$this->active_asset,
        ));
      } // if
      
      if($this->comments_delegate instanceof CommentsController) {
        $this->comments_delegate->__setProperties(array(
          'active_object' => &$this->active_asset, 
        ));
      } // if
        
      if($this->subscriptions_delegate instanceof SubscriptionsController) {
        $this->subscriptions_delegate->__setProperties(array(
          'active_object' => &$this->active_asset, 
        ));
      } // if

      if($this->reminders_delegate instanceof RemindersController) {
      	$this->reminders_delegate->__setProperties(array(
          'active_object' => &$this->active_asset,
        ));
      } // if
      
      if($this->sharing_settings_delegate instanceof SharingSettingsController) {
      	$this->sharing_settings_delegate->__setProperties(array(
          'active_object' => &$this->active_asset,
        ));
      } // if
    } // __before
    
    /**
     * List all project bookmarks (API & phone requests only)
     */
    function index() {
    	
    	// Phone call
    	if($this->request->isPhone()) {
    		if(ProjectAssets::canAdd($this->logged_user, $this->active_project)) {
      		$this->wireframe->actions->add('add_bookmark', lang('New Bookmark'), Router::assemble('project_assets_bookmark_add', array('project_slug' => $this->active_project->getSlug())), array(
            'icon' => AngieApplication::getImageUrl('layout/button-add.png', ENVIRONMENT_FRAMEWORK, AngieApplication::INTERFACE_PHONE),
            'primary' => true
	        ));
    		} // if
        
    		$this->response->assign('bookmarks', ProjectAssets::findByTypeAndProject($this->active_project, 'Bookmark', STATE_VISIBLE, $this->logged_user->getMinVisibility()));
    		
    	// Tablet device
    	} elseif($this->request->isTablet()) {
    		throw new NotImplementedError(__METHOD__);
    		
    	// API call
    	} elseif($this->request->isApiCall()) {
        throw new NotImplementedError(__METHOD__);
      } else {
        $this->response->badRequest();
      } // if
    } // index
    
    /**
     * Show archived bookmarks (mobile devices only)
     */
    function archive() {
      if($this->request->isMobileDevice()) {
        $this->response->assign('bookmarks', ProjectAssets::findArchivedByTypeAndProject($this->active_project, 'Bookmark', STATE_ARCHIVED, $this->logged_user->getMinVisibility()));
      } else {
        $this->response->badRequest();
      } // if
    } // archive
  	
  	/**
  	 * View bookmark
  	 */
  	function view() {
  	  if($this->active_asset->isLoaded()) {
  	    if($this->active_asset->canView($this->logged_user)) {
  	      if($this->request->isApiCall()) {
  	        $this->response->respondWithData($this->active_asset, array(
              'as' => 'bookmark', 
  	          'detailed' => true, 
            ));
  	      } // if
  	      
  	      $this->wireframe->setPageObject($this->active_asset, $this->logged_user);
      
          // Phone request
          if($this->request->isPhone()) {
          	$this->wireframe->actions->remove(array('pin_unpin', 'favorites_toggler'));
          } elseif($this->request->isSingleCall()) {
            $this->active_asset->accessLog()->log($this->logged_user);
          	$this->render();
          } else {
            if ($this->active_asset->getState() == STATE_ARCHIVED) {
              parent::archive();
              parent::render(get_view_path('archive', 'assets', FILES_MODULE));
            } else {
              parent::index();
              parent::render(get_view_path('index', 'assets', FILES_MODULE));
            } // if
          } // if
          
  	    } else {
        	$this->response->forbidden();
        } // if
  	  } else {
  	    $this->response->notFound();
  	  } // if
  	} // view
  	
  	/**
  	 * Add new bookmark
  	 */
  	function add() {
  	  if($this->request->isAsyncCall() || ($this->request->isApiCall() && $this->request->isSubmitted()) || $this->request->isMobileDevice()) {
  	    if(ProjectAssets::canAdd($this->logged_user, $this->active_project)) {
  	      $bookmark_data = $this->request->post('bookmark', array(
          	'visibility' => $this->active_project->getDefaultVisibility()
          ));
          
          $this->response->assign(array(
      			'bookmark_data' => $bookmark_data,
      			'add_bookmark_url' => Router::assemble('project_assets_bookmark_add', array('project_slug' => $this->active_project->getSlug()))
      		));
      		
      		if ($this->request->isSubmitted()) {
          	try {
          		DB::beginWork('Creating new bookmark @ ' . __FILE__);
          		
          		$this->active_asset->setAttributes($bookmark_data);
          		$this->active_asset->setState(STATE_VISIBLE);
          		
          		$this->active_asset->save();
          		
          		DB::commit('New bookmark created @ ' . __FILE__);
          		
          		// Set subscriptions
              $this->active_asset->subscriptions()->set(array_unique(array_merge(
                (array) $this->logged_user->getId(),
                (array) $this->active_project->getLeaderId(),
                (array) $this->request->post('notify_users', array())
              )), false);
              
              $this->logged_user->notifier()->notifySubscribers($this->active_asset, 'files/new_bookmark');
              
              if($this->request->isPageCall()) {
                $this->response->redirectToUrl($this->active_asset->getViewUrl());
              } else {
                $this->response->respondWithData($this->active_asset, array(
                  'as' => 'bookmark', 
                  'detailed' => true, 
                ));
              } // if
          	} catch (Exception $e) {
          		DB::rollback('Failed to create new bookmark @ ' . __CLASS__);
            	
            	if($this->request->isPageCall()) {
                $this->response->assign('errors', $e);
              } else {
                $this->response->exception($e);
              } // if
          	} // try
          } // if
  	    } else {
        	$this->response->forbidden();
        } // if
  	  } else {
  	    $this->response->badRequest();
  	  } // if
  	} // add
  	
  	/**
  	 * Edit existing bookmark
  	 */
  	function edit() {
  	  if($this->request->isAsyncCall() || ($this->request->isApiCall() && $this->request->isSubmitted()) || $this->request->isMobileDevice()) {
  	    if($this->active_asset->isLoaded()) {
  	      if($this->active_asset->canEdit($this->logged_user)) {
  	        $bookmark_data = $this->request->post('bookmark', array(
      				'name' => $this->active_asset->getName(),
      				'body' => $this->active_asset->getBody(),
      				'bookmark_url' => $this->active_asset->getBookmarkUrl(),
      				'category_id' => $this->active_asset->getCategoryId(),
      				'milestone_id' => $this->active_asset->getMilestoneId(),
      				'visibility' => $this->active_asset->getVisibility(),
            ));
            
            $this->response->assign(array(
            	'bookmark_data' => $bookmark_data
            ));
            
            if ($this->request->isSubmitted()) {     
            	try {
            		$this->active_asset->setAttributes($bookmark_data);
            		$this->active_asset->save();
            		
            		if($this->request->isPageCall()) {
                  $this->response->redirectToUrl($this->active_asset->getViewUrl());
                } else {
                  $this->response->respondWithData($this->active_asset, array(
                    'as' => 'bookmark', 
                    'detailed' => true, 
                  ));
                } // if
            	} catch (Exception $e) {
            		if($this->request->isPageCall()) {
                  $this->response->assign('errors', $e);
                } else {
                  $this->response->exception($e);
                } // if
            	} // try
            } // if
  	      } else {
          	$this->response->forbidden();
          } // if
  	    } else {
          $this->response->notFound();
        } // if
  	  } else {
  	    $this->response->badRequest();
  	  } // if
  	} // edit
    
  }