<?php

/**
 * materio_flag_refresh_blocks($flag)
 * 
 */
function materio_flag_refresh_block($flag){
	
	switch ($flag) {
		case 'bookmarks':
			$block_name = 'materio_flag_mybookmarks';
			break;
	case 'lists':
		$block_name = 'materio_flag_mylists';
    $block_nav_name = 'materio_flag_mylists_nav';
		break;
	}

	if(!isset($block_name))
		return;
	
	$rep = array();

	$block = block_load('materio_flag', $block_name);
	$block_content = _block_render_blocks(array($block));
	$build = _block_get_renderable_array($block_content);
	$block_rendered = drupal_render($build);
  $rep['block'] = $block_rendered;

  if(isset($block_nav_name))
    $block = block_load('materio_flag', $block_nav_name);
    $block_content = _block_render_blocks(array($block));
    $build = _block_get_renderable_array($block_content);
    $block_rendered = drupal_render($build);
    $rep['block_nav'] = $block_rendered;


 	drupal_json_output($rep);
}

/**
 * materio_flag_createlist($type)
 * 
 */
function materio_flag_createlist_form($type){
  $debug = false;

	$path = 'flag-lists/add/' . $type;

  // check if request is ajax, if not rediret
  if (!$debug && (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')) {
    drupal_goto('flag-lists/add/' . $type);
    exit ;
  }

  // menu_set_active_item($path);
  // $return = menu_execute_active_handler($path, FALSE);
  
  // if (is_int($return)) {
  //   switch ($return) {
  //     case MENU_NOT_FOUND :
  //       drupal_add_http_header('Status', '404 Not Found');
  //       break;
  //     case MENU_ACCESS_DENIED :
  //       drupal_add_http_header('Status', '403 Forbidden');
  //       break;
  //     case MENU_SITE_OFFLINE :
  //       drupal_add_http_header('Status', '503 Service unavailable');
  //       break;
  //   }
  // } elseif (isset($return)) {
  
  // $form_state['build_info']['args'] = array(NULL, 'breve');
  // $f = drupal_get_form('flag_lists_form', $form_state);
  // dsm($f);

  $form = array(
    '#type' => 'form',
    '#id' => 'materio-flag-create-list-form',
  );

  $form['type'] = array(
    '#type' => 'hidden',
    '#value' => $type,
    '#name' => 'type',
  );

  $form['listname'] = array(
    '#type' => 'textfield', 
    '#title' => t('Create new @name', array('@name'=>variable_get('flag_lists_name', 'list'))),
    '#default_value' => '', 
    // '#size' => 100, 
    '#maxlength' => 255, 
    '#name' => 'flag-lists-name',
    '#description' => t('A short, descriptive title for this Folder list. Limit to 255 characters.'),
  );

  $form['actions'] = array(
    '#prefix' => '<div class="actions">',
    '#suffix' => '</div>',
  );

  $form['actions']['create'] = array(
    '#type' => 'submit',
    '#value' => t('create'),
    '#name' => 'create',
  );

  $form['actions']['cancel'] = array(
    '#type' => 'button',
    '#value' => t('cancel'),
    '#name' => 'cancel',
  );
  

  // dsm($form, 'form');

  $return = drupal_render($form); 

  $rep = array(
    'return'=>$return,
  );
  
  if ($debug) {
    dsm($rep, 'rep');
    return "debug display";
  }else{
    drupal_json_output($rep);  
  }

}

/**
 * materio_flag_editlist_form()
 */
function materio_flag_editlist_form($type, $fid){
  $debug = false;

  $path = 'flags/lists/edit/' . $fid;

  // check if request is ajax, if not rediret
  if (!$debug && (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')) {
    drupal_goto($path);
    exit ;
  }

  // If name is numeric, then we have the fid, so get the name.
  if (is_numeric($fid)) {
    $name = db_select('flag_lists_flags', 'f')
      ->fields('f', array('name'))
      ->condition('fid', $fid)
      ->execute()
      ->fetchField();
  }

  if(flag_lists_is_owner('edit', $fid)){

    $flag = flag_lists_get_flag($name);

    $form = array(
      '#type' => 'form',
      '#id' => 'materio-flag-edit-list-form',
    );

    $form['type'] = array(
      '#type' => 'hidden',
      '#value' => $type,
      '#name' => 'type',
    );

    $form['fid'] = array(
      '#type' => 'hidden',
      '#value' => $fid,
      '#name' => 'fid',
    );
    
    $form['name'] = array(
      '#type' => 'hidden',
      '#value' => $name,
      '#name' => 'name',
    );

    $form['listtitle'] = array(
      '#type' => 'textfield', 
      '#title' => t('Edit this '.variable_get('flag_lists_name', 'list')),
      '#value' => $flag->title, 
      // '#size' => 100, 
      '#maxlength' => 255, 
      '#name' => 'flag-lists-title',
      '#description' => t('A short, descriptive title for this Folder list. Limit to 255 characters.'),
    );

    $form['actions'] = array(
      '#prefix' => '<div class="actions">',
      '#suffix' => '</div>',
    );

    $form['actions']['save'] = array(
      '#type' => 'submit',
      '#value' => t('save'),
      '#name' => 'save',
    );

    $form['actions']['delete'] = array(
      '#type' => 'submit',
      '#value' => t('delete'),
      '#name' => 'delete',
    );

    $form['actions']['cancel'] = array(
      '#type' => 'button',
      '#value' => t('cancel'),
      '#name' => 'cancel',
    );
    
    // dsm($form, 'form');

    $return = drupal_render($form); 

    $rep = array(
      'return'=>$return,
    );
  }else{
    $rep = array(
      'status' => 'error',
      'message' => t('you do not have rights to edit this '.variable_get('flag_lists_name', 'list')),
    );
  }
  
  if ($debug) {
    dsm($rep, 'rep');
    return "debug display";
  }else{
    drupal_json_output($rep);  
  }
}

function materio_flag_edit_list($fid, $name, $title){

  $path = 'flags/lists/edit/' . $fid;

  // check if request is ajax, if not rediret
  if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    drupal_goto($path);
    exit ;
  }

  if(!flag_lists_is_owner('edit', $fid)){
    $rep = array(
      'error' => true,
      'message' => t('You have not enough rights to edit this @name.', array('@name' => variable_get('flag_lists_name', t('list'))))
    );
  }else if (flag_lists_title_exists($title, 'materiau') || flag_lists_title_exists($title, 'breve')){
    $rep = array(
      'error' => true,
      'message' => t('You already have a @name with this name.', array('@name' => variable_get('flag_lists_name', t('list'))))
    );
  }else{

    $flag = flag_lists_get_flag($name);
    $flag->title = $title;
    flag_lists_set_messages($flag);
    flag_lists_save($flag);
    _flag_lists_clear_cache();

    $rep = array(
      'status' => 'saved',
      'listname' => $name,
      'listtitle' => $title,
    );

  }

  drupal_json_output($rep);  
}

function materio_flag_delete_list($fid){
  $path = 'flags/lists/delete/' . $fid;

  // check if request is ajax, if not rediret
  if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    drupal_goto($path);
    exit ;
  }

  if(!flag_lists_is_owner('delete', $fid)){
    $rep = array(
      'error' => true,
      'message' => t('You have not enough rights to delete this @name.', array('@name' => variable_get('flag_lists_name', t('list'))))
    );
  }else{

    // If name is numeric, then we have the fid, so get the name.
    if (is_numeric($fid)) {
      $name = db_select('flag_lists_flags', 'f')
        ->fields('f', array('name'))
        ->condition('fid', $fid)
        ->execute()
        ->fetchField();
    }

    $flag = flag_lists_get_flag($name);
    
    flag_lists_fl_delete($flag);  

    $rep = array(
      'status' => 'saved',
    );
  }

  drupal_json_output($rep); 
}

function materio_flag_nodelinks(){
  $nids = explode(';', $_REQUEST['nids']);

  if(count($nids)){
    foreach ($nids as $nid) {
      $node = node_load($nid);
      $lks = render(materio_flag_get_entity_links($node, 'node'));
      $links[$nid] = $lks;
    }

    $rep = array(
      "status" => 1,
      "nids" => $nids,
      'links' => $links,
    );  
  }else{
    $rep['status'] = 0;
  }

  drupal_json_output($rep);  
}

function materio_flag_user_lists($fid){
  global $user;
  $flag = flag_lists_get_flag($fid);
  // dsm($flag, 'flag');

  drupal_set_title(_materio_flag_get_listpagetitle($flag), PASS_THROUGH);

  $flaged_content = flag_lists_get_flagged_content($fid, $user->uid);
  // dsm($flaged_content, 'flaged_content');

  $viewmode = isset($user->data['materiosearchapi_viewmode']) ? $user->data['materiosearchapi_viewmode'] : variable_get('defaultviewmode', 'full');

  $limit = variable_get($viewmode.'_limite', '10');
  $offset = pager_find_page() * $limit;
  $count = count($flaged_content);
  $max = $offset+$limit > $count ? $count : $offset+$limit;

  for ($i=$offset; $i < $max; $i++) { 
    if($flaged_content[$i]->entity_type == 'node'){
      $items[] = node_load($flaged_content[$i]->entity_id);
    }
  }  
  
  $ret['#items'] = $items;
  $ret['#theme'] = 'materio_flag_mylists_list';
  $ret['#view_mode'] = $viewmode;
  $ret['#fid'] = $fid;
  $ret['#count'] = $count;
  $ret['#name'] = variable_get('flag_lists_name', 'list');
  $ret['#title'] = $flag->title;

  pager_default_initialize($count, $limit);
  $ret['#pager'] = theme('pager');

  return $ret;

}

function materio_flag_ajax_list($fid, $page = 0){
  $debug = false;

  $_GET['page'] = $page;

  $list_path = 'lists';

  $path = $list_path.'/'.$fid;

  // check if request is ajax, if not rediret to search_api_page page with right keys
  if (!$debug && (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')) {
    drupal_goto($path, array('query'=>array('page'=>$page)), 301);
    exit;
  }

  if(isset($_GET['current_path'])){
    // dsm($_GET['current_path'], '$_GET[current_path]');
    // url() generates the prefix using hook_url_outbound_alter(). Instead of
    // running the hook_url_outbound_alter() again here, extract the prefix
    // from url().
    url('', array('prefix' => &$prefix));

    $cur_path = str_replace($base_url.base_path().$prefix, '', $_GET['current_path']);
    // dsm($cur_path, 'cur_path');

    $cur_is_list_path = strpos($cur_path, $list_path);
    // dsm($matches, '$matches');
    if($cur_is_list_path === false){
      $rep = array(
        "redirect" => $base_url.base_path().$prefix.$path,
      );
      drupal_json_output($rep);
      exit;
    }
  }


  // get results
  menu_set_active_item($path);
  $return = menu_execute_active_handler($path, FALSE);

  // dsm($return, '$return');
  
  if (is_int($return)) {
    switch ($return) {
      case MENU_NOT_FOUND :
        drupal_add_http_header('Status', '404 Not Found');
        break;
      case MENU_ACCESS_DENIED :
        drupal_add_http_header('Status', '403 Forbidden');
        break;
      case MENU_SITE_OFFLINE :
        drupal_add_http_header('Status', '503 Service unavailable');
        break;
    }
  } elseif (isset($return)) {

    if (is_array($return)) {
      $return = drupal_render($return);
    }
      
    $rep = array(
      'return' => $return,
      'path' => $path,
      'title' => drupal_get_title(),
    );
    
    if ($debug) {
      dsm($rep, 'rep');
      return "debug display";
    }else{
      drupal_json_output($rep);  
    }
  }
}