<?php

/**
 * @file
 * The Flag bookmark module.
 *
 * This module creates a default Flag when enabled.
 * 
 */

/**
 * Implements hook_permission().
 */
function materio_flag_permission() {
  return array(
    /*
     *'administer my module' =>  array(
     *  'title' => t('Administer my module'),
     *  'description' => t('Perform administration tasks for my module.'),
     *),
     */
    // 'access mybookmarks block' =>  array(
    //   'title' => t('Show my bookmarks block'),
    //   'description' => t('access own bookmarks block'),
    // ),
  );
}

/**
 * Implements hook_menu().
 */
function materio_flag_menu() {
  $items = array();

  $base = array(
    'type' => MENU_CALLBACK,
    'file' => 'materio_flag.pages.inc',
  );

  $items['materioflag/refresh/block/bookmarks'] = $base+array(
    'access arguments' => array('flag bookmarks'),
    'page callback' => 'materio_flag_refresh_block',
    'page arguments' => array(3),
  );

  $items['bookmarks'] = $base+array(
    'access arguments' => array('flag bookmarks'),
    'page callback' => 'materio_flag_user_bookmarks',
    'page arguments' => array(),
  );

  $items['materioflag/refresh/block/lists'] = $base+array(
    'access arguments' => array('create flag lists'),
    'page callback' => 'materio_flag_refresh_block',
    'page arguments' => array(3),
  );

  $items['materioflag/createlist/form/%'] = $base+array(
    'access arguments' => array('create flag lists'),
    'access callback' => 'user_access',
    'page callback' => 'materio_flag_createlist_form',
    'page arguments' => array(3),
  );
  
  $items['materioflag/editlistform/%/%'] = $base+array(
    'access arguments' => array('create flag lists'),
    'access callback' => 'user_access',
    'page callback' => 'materio_flag_editlist_form',
    'page arguments' => array(2,3),
  );
  
  $items['materioflag/editlist/%/%'] = $base+array(
    'access arguments' => array('create flag lists'),
    'access callback' => 'user_access',
    'page callback' => 'materio_flag_edit_list',
    'page arguments' => array(2,3),
  );

  $items['materioflag/deletelist/%'] = $base+array(
    'access arguments' => array('create flag lists'),
    'access callback' => 'user_access',
    'page callback' => 'materio_flag_delete_list',
    'page arguments' => array(2,3),
  );

  $items['materioflag/nodelinks'] = $base+array(
    'access arguments' => array('create flag lists'),
    'access callback' => 'user_access',
    'page callback' => 'materio_flag_nodelinks',
    // 'page arguments' => array(3),
  );
  
  $items['lists/%'] = $base+array(
    'access arguments' => array('view flag lists'),
    'access callback' => 'user_access',
    'page callback' => 'materio_flag_user_lists',
    'page arguments' => array(1),
  );

   $items['materioflag/ajax/list/%'] = $base+array(
    'page callback' => 'materio_flag_ajax_list',
    'access callback' => 'materio_access_ajax_flags',
    'page arguments' => array(3, 4),
  );

  return $items;
}

function materio_access_ajax_flags(){
  return user_access('create flag lists') || user_access('flag bookmarks');
}

/**
 * Implements hook_menu_alter().
 */
function materio_flag_menu_alter(&$items) {
  // Example - disable the page at node/add
  /*
   *$items['node/add']['access callback'] = FALSE;
   */
  // disable tabs on user page
  $items['user/%user/flags/lists']['access callback'] = false;
  $items['user/%user/flags/lists/%']['access callback'] = false;
}

/**
 * Implements hook_block_info().
 */
function materio_flag_block_info() {
  
  $blocks['materio_flag_mybookmarks'] = array(
    'info' => t('My bookmarks'),
    'cache' => DRUPAL_NO_CACHE
  );

 $blocks['materio_flag_mylists'] = array(
    'info' => t('My Materio flag lists'),
    'cache' => DRUPAL_NO_CACHE
  );

  $blocks['materio_flag_mylists_nav'] = array(
    'info' => t('My Materio flag lists navigation'),
    'cache' => DRUPAL_NO_CACHE
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function materio_flag_block_view($delta = '') {
  global $user;

  $block = array();

  switch ($delta) {
    case 'materio_flag_mybookmarks':
      if(user_access('access mybookmarks block')){
        $userflags = flag_get_user_flags('node');
        //dsm($userflags, 'userflags');
        if(isset($userflags['bookmarks'])){
        	$userbookmarks = array();
  	      foreach ($userflags['bookmarks'] as $nid => $flag) {
        		$userbookmarks[] = node_load($nid);
  	      }
          // TODO:  put this title generation on a theme function
          $subject = '<span class="listname">'.t('My bookmarks (@len) ', array("@len"=>count($userbookmarks))).'</span>';
  	      $block['subject'] = $subject . l('<i class="icon-resize-full"></i>', 'bookmarks', array('html'=>true, 'attributes' => array('class' => array('open-list')),)); // 
  	      $block['content'] = theme('materio_flag_mybookmarks_block', array("bookmarks"=>$userbookmarks, "viewmode"=>"bookmark"));
        }else{
        	$block['subject'] = t('My bookmarks');
        	$block['content'] = t('No bookmarks yet. Add bookmarks on clicking on results star');
        }
        drupal_add_js(drupal_get_path('module', 'materio_flag').'/js/materio_flag-ck.js');
      }
      break;
    case 'materio_flag_mylists':
      if(user_access('create flag lists')){
        $flags = flag_lists_get_user_flags(NULL, $user);
        // $userflags = flag_get_user_flags('node');
        // dsm($userflags, 'userflags');
        // dsm($flags, 'flags');
        
        foreach ($flags as $name => $flag) {
          $flag->path = url('lists/'.$flag->fid);
          $flaged_content = flag_lists_get_flagged_content($flag->fid, $user->uid);
          // dsm($flaged_content, 'flaged_content');
          $fcn = array();
          foreach ($flaged_content as $entity) {
            if($entity->entity_type == 'node'){
              $node = node_load($entity->entity_id);
              // dsm($node, 'node');

              // $node->flag_names[] = $name;
              $fcn[] = $node;
            }
          }

          $lists[$name] = array(
            'list' => $flag,
            'content' => $fcn,
          );
        }

        if(isset($lists)){
          // $block['subject'] = t('My !listname'.'s', array('!listname'=>t(variable_get('flag_lists_name', 'list'))));
          $block['subject'] = t('My '.variable_get('flag_lists_name', 'list').'s');
          $block['content'] = theme('materio_flag_mylists_block', array("lists"=>$lists, "viewmode"=>"bookmark"));
          // $block['content'] = theme('flag_lists_user_page', array('uid' => $user->uid));
        }else{

          $block['subject'] = t('My '. variable_get('flag_lists_name', 'list') .'s');
          $block['content'] = t('No !listname yet. Add !listname on clicking on results star', array('!listname'=>variable_get('flag_lists_name', 'list')));
        }
        drupal_add_js(drupal_get_path('module', 'materio_flag').'/js/materio_flag-ck.js');
      }
      break;
    case 'materio_flag_mylists_nav':
      if(user_access('create flag lists')){
        $flags = flag_lists_get_user_flags(NULL, $user);

        foreach ($flags as $name => $flag) {
          $flaged_content = flag_lists_get_flagged_content($flag->fid, $user->uid);
          $flag->flaged_content = $flaged_content;
          $flags[$name] = $flag;
        }
        // if($flags){
          // $block['subject'] = t('My !listname'.'s', array('!listname'=>variable_get('flag_lists_name', 'list')));
          $block['subject'] = t('My '.variable_get('flag_lists_name', 'list').'s');
        
          $block['content'] = theme('materio_flag_mylists_nav_block', array("flags"=>$flags));
          // $block['content'] = theme('flag_lists_user_page', array('uid' => $user->uid));
        // }
        # what happend if no flags yet
        // else{
        //   $block['subject'] = t('My '.variable_get('flag_lists_name', 'list').'s');
        // //   $block['content'] = t('No !listname yet. Add !listname on clicking on results star', array('!listname'=>variable_get('flag_lists_name', 'list')));
        // }
      }
      break;
  }
  return $block;
}

/**
 * Implements hook_entity_info_alter().
 */
function materio_flag_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['bookmark'] = array(
    'label' => t('Bookmark'),
    'custom settings' => TRUE,
  );
}

/**
 * Implements hook_entity_view().
 *
 * Note this is broken for taxonomy terms. @see http://drupal.org/node/1067120
 */
function materio_flag_entity_view($entity, $type, $view_mode, $langcode) {
  if($type == 'node'){
    if(user_access('create flag lists') && $view_mode != 'print'){
      
      $entity->content['flaglistslinks'] = materio_flag_get_entity_links($entity, $type, $view_mode);

      drupal_add_css(drupal_get_path('module', 'flag') . '/theme/flag.css');
      drupal_add_js(drupal_get_path('module', 'flag') . '/theme/flag.js');

      // Do we have a list template for this node type, or are we s
      if (flag_lists_template_exists($entity->type)) {
        global $user;
        if ($flags = flag_lists_get_user_flags($entity->type, $user)) {
          foreach ($flags as $flag) {
            // dsm($flag, 'flag');
            if ( ($flag->module == 'flag_lists' && _flag_lists_is_flagged($flag, $entity->nid, $user->uid, 0)) || $flag->is_flagged($entity->nid) ) {
              $entity->flags[] = $flag;      
            }
          }
        }
      }
      
    }
  }
}

function materio_flag_get_entity_links($entity, $type, $view_mode = null){
  // dsm($entity, 'entity');

  // Do we have a list template for this node type, or are we s
  if (!flag_lists_template_exists($entity->type)) {
    return;
  }

  global $user;
  $links = array();
  # if flag name is provided we are on flaglists content list (block mylists)
  if($view_mode == 'bookmark'){
    // TODO:  define view mode in settings  
    // if (isset($entity->flag_names) && $flags = flag_lists_get_user_flags($entity->type, $user)) {
    //   // dsm($flags, 'flags');
    //   // TODO:  limit flag link by current flag list  
    //   foreach ($flags as $flag) {
    //     //dsm($flag->name, 'flag');
    //     if(in_array($flag->name, $entity->flag_names)){
    //       if ($flag->module == 'flag_lists') {
    //         $action = _flag_lists_is_flagged($flag, $entity->nid, $user->uid, 0) ? 'unflag' : 'flag';
    //       } else {
    //         $action = $flag->is_flagged($entity->nid) ? 'unflag' : 'flag';
    //       }  
    //       $flag->module = 'materio_flag';
    //       $link = $flag->theme($action, $entity->nid);

    //       // If it's a list, fix the link.
    //       if ($flag->module == 'flag_lists') {
    //         flag_lists_fix_link($link, $action);
    //       }

    //       $items[] = array(
    //         'data' => $link,
    //         'class' => array('flag-lists-link', $action.'-action'),
    //       );

    //       // array_splice($entity->flag_names, array_search($flag->name, $entity->flag_names), 1);
    //       // dsm($entity->flag_names, 'entity->flag_name');
    //       // break;
    //     }
    //   }
    // }
  #normal display
  }else{
    if ($flags = flag_lists_get_user_flags($entity->type, $user)) {
      // dsm($flags, 'flags');
      // Build the list of lists for this node.
      foreach ($flags as $flag) {
        // dsm($flag, 'flag');
        if ($flag->module == 'flag_lists') {
          $action = _flag_lists_is_flagged($flag, $entity->nid, $user->uid, 0) ? 'unflag' : 'flag';
        }
        else {
          $action = $flag->is_flagged($entity->nid) ? 'unflag' : 'flag';;
        }

        $link = $flag->theme($action, $entity->nid);

        // If it's a list, fix the link.
        if ($flag->module == 'flag_lists') {
          flag_lists_fix_link($link, $action);
        }

        $items[] = array(
          'data' => $link,
          'class' => array('flag-lists-link', $action.'-action', 'fid-'.$flag->fid),
        );

      }
    }
    
    // dsm($items, 'items '.$entity->title);

    #create new list
    $link = l(
      '<i class="icon-plus"></i>&nbsp;<span>' . t('New @name', array('@name' => t(variable_get('flag_lists_name', 'list')))) . '</span>', 
      'flag-lists/add/' . $entity->type,
      array(
        'attributes' => array(
          'class' => array('flag-lists-create'),
          'title' => t('create a new @name and use it.', array('@name'=>t(variable_get('flag_lists_name', 'list')))),
          'nid' => $entity->nid,
          'token' => flag_get_token($entity->nid),
        ),
        'html' => TRUE,
      )
    );
    
    $create = array(
      'data' => $link,
      'class' => array('flag-lists-create'),
    );
  }

  if(isset($items)){
    $ops = array(
      '#node' => $entity, 
      '#items' => $items,
    );
  }
  
  if(isset($create)){ 
    $ops['#create'] = $create;
  }
  
  if(isset($ops)){
    // dsm($ops, 'ops');
    drupal_add_js(drupal_get_path('module', 'materio_flag').'/js/materio_flag-ck.js');
    $ops['#theme'] = "materio_flag_mylists_entity_links";
    return $ops;
  }

  return;
}

function _materio_flag_get_listpagetitle($flag){
  $cont = '<i class="icon-materio-folder"></i>';
  $cont .= '<span class="'.$flag->name.'">'.check_plain($flag->title).'</span>';
  
  if(flag_lists_is_owner('edit', $flag->fid)){
          
    $cont .= l('<i class="icon-wrench"></i>', 
                'flags/lists/edit/'.$flag->fid, 
                array(
                  'html'=>true,
                  'attributes'=>array('class'=>array('edit-list', $flag->name)),
                )
              ); 
  }
        
  
  return $cont;
}


/**
 * Implements hook_theme().
 */
function materio_flag_theme($existing, $type, $theme, $path) {
  return array(
    'materio_flag_mybookmarks_block' => array(
      'arguments' => array(),
      'template' => 'materio-flag-mybookmarks-block',
      'path' => drupal_get_path('module', 'materio_flag').'/templates',
    ),
    'materio_flag_mylists_block' => array(
      'arguments' => array(),
      'template' => 'materio-flag-mylists-block',
      'path' => drupal_get_path('module', 'materio_flag').'/templates',
    ),
    'materio_flag_mylists_nav_block' => array(
      'arguments' => array(),
      'template' => 'materio-flag-mylists-nav-block',
      'path' => drupal_get_path('module', 'materio_flag').'/templates',
    ),
    'materio_flag_mylists_entity_links' => array(
      'variables' => array('node' => NULL, 'create' => NULL, 'items' => array()),
    ),
    'materio_flag_mylists_list' => array(
      'template' => 'materio-flag-mylists-list',
      'path' => drupal_get_path('module', 'materio_flag').'/templates',
      'variables' => array(
        'count' => 0,
        'items' => array(),
        'view_mode' => 'teaser',
        'pager' => NULL,
        'fid' => null,
        'name' => null,
        'title' => null,
      ),
    ),
  );
}

function template_preprocess_materio_flag_mybookmarks_block(&$vars){
	// dsm($vars, 'vars');
}


function template_preprocess_materio_flag_mylists_block(&$vars){
  // dsm($vars, 'vars');
}

function template_preprocess_materio_flag_mylists_nav_block(&$vars){
  // dsm($vars, 'vars');
}

/**
 * theme_materio_flag_mylists_entity_links()
 * 
 * see theme_flag_lists_list()
 */
function theme_materio_flag_mylists_entity_links($vars){
  
  // $node = $vars['node'];
  $items = $vars['items'];

  // dsm($vars, 'vars HO');

  if(isset($vars['create']))
    $items[] = $vars['create'];
  
  return theme('item_list', array('items' => $items, 'type' => 'ul', 'attributes' => array('class' => 'flag-lists-entity-links')));

}

function template_preprocess_materio_flag_mylists_list(&$vars) {
  
  $vars['list_count'] = format_plural(
    $vars['count'],
    '@name @title contains 1 item.', // in @sec seconds
    '@name @title contains @count items.', // in @sec seconds
    array(
      '@name' => t($vars['name']),
      '@title' => $vars['title'],
    )
  );

  // dsm($vars, '$vars');
}

