<?php

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

  /**
   * YouTube videos controller
   *
   * @package activeCollab.modules.files
   * @subpackage controllers
   */
  class YouTubeVideosController extends AssetsController {
    
    /**
     * Construct youtube videos controller
     *
     * @param Request $parent
     * @param mixed $context
     */
    function __construct(Request $parent, $context = null) {
      parent::__construct($parent, $context);
      
      if($this->getControllerName() == 'you_tube_videos') {
        $this->state_delegate = $this->__delegate('state', ENVIRONMENT_FRAMEWORK_INJECT_INTO, 'project_assets_you_tube_video');
        $this->comments_delegate = $this->__delegate('comments', COMMENTS_FRAMEWORK_INJECT_INTO, 'project_assets_you_tube_video');
        $this->subscriptions_delegate = $this->__delegate('subscriptions', SUBSCRIPTIONS_FRAMEWORK_INJECT_INTO, 'project_assets_you_tube_video');
				$this->reminders_delegate = $this->__delegate('reminders', REMINDERS_FRAMEWORK_INJECT_INTO, 'project_assets_you_tube_video');
				$this->move_to_project_delegate = $this->__delegate('move_to_project', SYSTEM_MODULE, 'project_assets_you_tube_video');
        $this->sharing_settings_delegate = $this->__delegate('sharing_settings', SYSTEM_MODULE, 'project_assets_you_tube_video');
      } // if
    } // __construct
    
    /**
     * Prepare controller
     */
    function __before() {
      parent::__before();
      
			if(!$this->active_asset || $this->active_asset->isNew()) {
        $this->active_asset = new YouTubeVideo();
        $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 YouTubeVideo)) {
        $this->httpError(HTTP_ERR_CONFLICT, 'Selected asset is not a YouTubeVideo');
      } // 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 youtube videos (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_you_tube_video', lang('New YouTube Video'), Router::assemble('project_assets_you_tube_video_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('you_tube_videos', ProjectAssets::findByTypeAndProject($this->active_project, 'YouTubeVideo', STATE_VISIBLE, $this->logged_user->getMinVisibility()));
    		
    	// Tablet device
    	} elseif($this->request->isTablet()) {
    		throw new NotImplementedError(__METHOD__);
    		
    	// API call
    	} elseif($this->request->isApiCall()) {
        $this->response->respondWithData(ProjectAssets::findByTypeAndProject($this->active_project, 'YouTubeVideo', STATE_VISIBLE, $this->logged_user->getMinVisibility()), array(
          'as' => 'you_tube_videos', 
        ));
      } else {
        $this->response->badRequest();
      } // if
    } // index
    
    /**
     * Show archived youtube videos (mobile devices only)
     */
    function archive() {
      if($this->request->isMobileDevice()) {
        $this->response->assign('you_tube_videos', ProjectAssets::findArchivedByTypeAndProject($this->active_project, 'YouTubeVideo', STATE_ARCHIVED, $this->logged_user->getMinVisibility()));
      } else {
        $this->response->badRequest();
      } // if
    } // archive
  	
  	/**
  	 * View youtube video
  	 */
  	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' => 'you_tube_video', 
              '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->isWebBrowser()) {
            if($this->request->isSingleCall() || $this->request->isQuickViewCall()) {
            	$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
          } // if
  	    } else {
        	$this->response->forbidden();
        } // if
  	  } else {
  	    $this->response->notFound();
  	  } // if
  	} // view
  	
  	/**
  	 * Add new youtube video
  	 */
  	function add() {
  	  if ($this->request->isAsyncCall() || ($this->request->isApiCall() && $this->request->isSubmitted()) || $this->request->isMobileDevice()) {
  	    if (ProjectAssets::canAdd($this->logged_user, $this->active_project)) {
  	      $youtube_data = $this->request->post('youtube_video', array(
          	'visibility' => $this->active_project->getDefaultVisibility()
          ));
          
          $this->response->assign(array(
      			'youtube_data' => $youtube_data,
      			'add_youtube_url' => Router::assemble('project_assets_you_tube_video_add', array('project_slug' => $this->active_project->getSlug()))
      		));
      		
      		if($this->request->isSubmitted()) {
          	try {
          		DB::beginWork('Creating a new YouTube video @ ' . __FILE__);
          		
          		// @TODO FEATURE: implement validation with youtube servers for valid youtube video
          		$this->active_asset->setAttributes($youtube_data);
          		$this->active_asset->setState(STATE_VISIBLE);
          		
          		$this->active_asset->save();
          		
          		DB::commit('New YouTube video 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_you_tube_video');
              
              if($this->request->isPageCall()) {
                $this->response->redirectToUrl($this->active_asset->getViewUrl());
              } else {
                $this->response->respondWithData($this->active_asset, array(
                  'as' => 'you_tube_video', 
                  'detailed' => true, 
                ));
              } // if
          	} catch (Exception $e) {
          		DB::rollback('Failed to create a new YouTube video @ ' . __FILE__);
            	
            	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 youtube video
  	 */
  	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)) {
  	        $youtube_data = $this->request->post('youtube_video', array(
      				'name' => $this->active_asset->getName(),
      				'body' => $this->active_asset->getBody(),
      				'video_url' => $this->active_asset->getVideoUrl(),
      				'category_id' => $this->active_asset->getCategoryId(),
      				'milestone_id' => $this->active_asset->getMilestoneId(),
      				'visibility' => $this->active_asset->getVisibility(),
            ));
            
            $this->response->assign('youtube_data', $youtube_data);
            
            if ($this->request->isSubmitted()) {
            	try {
            		DB::beginWork('Updating a YouTube video @ ' . __FILE__);
            		
            		$this->active_asset->setAttributes($youtube_data);
            		$this->active_asset->save();
            		
            		DB::commit('YouTube video updated @ ' . __FILE__);
            		
            		if($this->request->isPageCall()) {
                  $this->response->redirectToUrl($this->active_asset->getViewUrl());
                } else {
                  $this->response->respondWithData($this->active_asset, array(
                    'as' => 'you_tube_video', 
                    'detailed' => true, 
                  ));
                } // if
            	} catch (Exception $e) {
            		DB::rollback('Failed to edit YouTube video @ ' . __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->notFound();
        } // if
  	  } else {
        $this->response->badRequest();
      } // if
  	} // edit
    
  }