<?php

/**
* perfart_get_dates()
*
*/
function perfart_get_dates($page = 0, $debug = false){
  // dsm($page, '$page');
  global $language;
  // dsm($language, '$language : '.$language->language);

  $query = new EffectuationEntityFieldQuery;
  $query
    ->range(PERFART_ELMTS_BY_PAGE*$page, PERFART_ELMTS_BY_PAGE);
    // ->pager(10, $page);
    // ->propertyOrderBy('created', 'DESC');
  
  $result = $query->execute();
  // dsm($result, '$result');
  
  $data = array();

  foreach ($result['node'] as $eff) {
    $eff = node_load($eff->nid);
    //$eff = entity_load('node', array($eff->nid), NULL, FALSE);
    // dsm($eff, '$eff');
    
    # dates
    if(!isset($eff->field_date_de_debut) || !isset($eff->field_performances))
      continue;
      
    $debut = $eff->field_date_de_debut['und'][0]['value'];

    //1969/06/06-18:00      
    $pattern = '/^(\d{4})\/?(\d{2})?\/?(\d{2})?-?(\d{2})?:?+(\d{2})?$/';
    
    preg_match($pattern, $debut, $debutMatches);
    
    if(!isset($debutMatches[1]))
      continue;
    
    if(isset($eff->field_date_de_fin['und'])){
      $fin = $eff->field_date_de_fin['und'][0]['value'];
      preg_match($pattern, $fin, $finMatches);
    }else{
      $fin = false;
    }
    
    # lieu
    $lieu_values = field_get_items('node',$eff,'field_lieu');
    $lieu_values = $lieu_values ? $lieu_values : array();
    // dsm($lieu_values, '$lieu_values');
    
    $lieu = array();
    foreach ($lieu_values as $value) {
      $term = taxonomy_term_load($value['tid']);
      if(!$term) continue;

      $term = i18n_taxonomy_localize_terms($term);
      // dsm($term, '$term');
      $lieu[$term->tid] = array(
        'tid' => $term->tid,
        'name' => t($term->name),
      );
    }
    
    # topologie
    $topologie_values = field_get_items('node',$eff,'field_topologie');
    // dsm($topologie_values, '$topologie_values');
    $topologies = array();
    if($topologie_values){
      foreach ($topologie_values as $value) {
        $term = taxonomy_term_load($value['tid']);
        if(!$term) continue;

        $term = i18n_taxonomy_localize_terms($term);

        $topologies[$term->tid] = array(
          'tid' => $term->tid,
          'name' => $term->name,
        );
      }
    }
    
    $perfadded = array();
    foreach ($eff->field_performances['und'] as $perf) {
      
      if(in_array($perf['target_id'], $perfadded))
        continue;
      
      $perfadded[] = $perf['target_id'];
      
      $perf = node_load($perf['target_id']);
      // $perf = entity_load('node', array($perf['target_id']), NULL, FALSE);
      // dsm($perf, '$perf');

      $prefix = $language->language == 'fr' ? 'en/' : '';

      $date = array(
        "nid"=>$perf->nid,
        "filters" => array(),
        'ajax_link'=> 'perfart/ajax/perf/'.$perf->nid,
        'node_link'=> drupal_get_path_alias('node/'.$perf->nid, $language->language),
        'node_translation'=> $prefix . drupal_get_path_alias('node/'.$perf->nid, $language->language == 'fr' ? 'en' : 'fr'),
        'perf_title'=>$perf->title,
        'language'=>$language,
      );
      
      #images
      if($images_values= field_get_items('node',$perf,'field_images')){
        //dsm($images_values, '$images_values');
        $image = theme('image_style', array(
          'style_name'=>'timeline_thumbnail', 
          'path'=>$images_values[0]['uri'],
        ));
        //$content .= $image;
        // dsm($image, 'image');
        $date['thumb'] = $image;
      }


      # timeline content + concepteurs filter
      $content = '<div href="perfart/ajax/perf/'.$perf->nid.'" class="date" nid="'.$perf->nid.'" >';//thumb="'.$date['thumb'].'"
      $content .= '<div class="text-content">';
      $content .= '<h4>'.$perf->title.'</h4>';
      
      #concepteur
      $concepteurs_values= field_get_items('node',$perf,'field_concepteur');
      $personnes = array();
      if($concepteurs_values){
        $concepteurs = array();
        foreach ($concepteurs_values as $concepteur) {
          $concepteur_term = taxonomy_term_load($concepteur['tid']);
          if(!$concepteur_term) continue;
          
          // dsm($concepteur_term);
          $field_nom_values = field_get_items('taxonomy_term', $concepteur_term , 'field_nom');
          $field_prenom_values = field_get_items('taxonomy_term', $concepteur_term, 'field_prenom');
          $concepteurs[] = $concepteur_term->name;
          $personnes[$concepteur_term->tid] = array(
            "tid" => $concepteur_term->tid,
            "name" => $concepteur_term->name,
            "nom" => $field_nom_values[0]['value'],
            "prenom" => $field_prenom_values[0]['value'],
          );
        }
        $content .= '<h5>'.implode(', ', $concepteurs).'</h5>';
      }
      $content .= '</div>';
      
      ## close content link
      $content .= '</div>';
      
      # timeline array with dates
      $date += array(
        'content'=> $content,
        'start'=>array(
          'year'=>$debutMatches[1],
          'month'=>isset($debutMatches[2]) ? $debutMatches[2] : null,
          'day'=>isset($debutMatches[3]) ? $debutMatches[3] : null,
        ),
      );
      
      if($fin && false) // deactivated end date because ranges cause display probleme on the timeline
        $date['end'] = array(
          'year'=>isset($finMatches[1]) ? $finMatches[1] : null,
          'month'=>isset($finMatches[2]) ? $finMatches[2] : null,
          'day'=>isset($finMatches[3]) ? $finMatches[3] : null,
        );
      
      # filter organisateur
      $organisateur_values= field_get_items('node',$perf,'field_organisateur');
      // dsm($organisateur_values, 'org');
      if($organisateur_values){
        foreach ($organisateur_values as $personne) {
          $term = taxonomy_term_load($personne['tid']);
          if(!$term) continue;
          
          // dsm($term);
          $field_nom_values = field_get_items('taxonomy_term', $term , 'field_nom');
          $field_prenom_values = field_get_items('taxonomy_term', $term, 'field_prenom');
          $personnes[$term->tid] = array(
            "tid" => $term->tid,
            "name" => $term->name,
            "nom" => $field_nom_values[0]['value'],
            "prenom" => $field_prenom_values[0]['value'],
          );
        }
      }
      
      # filter participants
      $participants_values= field_get_items('node',$perf,'field_participant');
      // dsm(count($participants_values), 'part');
      if($participants_values){
        foreach ($participants_values as $personne) {
          $term = taxonomy_term_load($personne['tid']);
          if(!$term) continue;
          
          // dsm($term);
          $field_nom_values = field_get_items('taxonomy_term', $term , 'field_nom');
          $field_prenom_values = field_get_items('taxonomy_term', $term, 'field_prenom');
          $personnes[$term->tid] = array(
            "tid" => $term->tid,
            "name" => $term->name,
            "nom" => $field_nom_values[0]['value'],
            "prenom" => $field_prenom_values[0]['value'],
          );
        }
      }
      
      
      # filter topologie flag
      $date["filters"]['topologies'] = $topologies;
      
      # filter lieu flag      
      $date['filters']['places'] = $lieu;
            
      # filter artistes
      $date['filters']['peoples'] = $personnes;
      
      
      $data[] = $date;
      
    }
  }

  // if($debug){
  //   dsm($data, '$data');
  //   return t('perfart_get_dates debug mode');
  // }else{
    drupal_json_output($data);      
  // }
}

/**
* perfart_get_perf()
* home page classical (no-js)
*
*/
function perfart_get_performances(){
  // dsm($page, '$page');
  global $language;
  // dsm($language, '$language : '.$language->language);

  $limit = 100;//variable_get($viewmode.'_limite', '10');
  $offset = pager_find_page() * $limit;

  $query = new EffectuationEntityFieldQuery;
  $query
    ->range($offset,$limit);
    // ->pager(10, $page);
    // ->propertyOrderBy('created', 'DESC');
  
  $result = $query->execute();
  // dsm($result, '$result');
  
  $count_query = new EffectuationEntityFieldQuery;
  $count = $count_query->count()->execute();
  pager_default_initialize($count, $limit);

  $data = array();

    foreach ($result['node'] as $eff) {
    $eff = node_load($eff->nid);
    //$eff = entity_load('node', array($eff->nid), NULL, FALSE);
    // dsm($eff, '$eff');
    
    # dates
    if(!isset($eff->field_date_de_debut) || !isset($eff->field_performances))
      continue;
      
    $debut = $eff->field_date_de_debut['und'][0]['value'];

    //1969/06/06-18:00      
    $pattern = '/^(\d{4})\/?(\d{2})?\/?(\d{2})?-?(\d{2})?:?+(\d{2})?$/';
    
    preg_match($pattern, $debut, $debutMatches);
    
    if(!isset($debutMatches[1]))
      continue;
    
    if(isset($eff->field_date_de_fin['und'])){
      $fin = $eff->field_date_de_fin['und'][0]['value'];
      preg_match($pattern, $fin, $finMatches);
    }else{
      $fin = false;
    }
    
    # lieu
    // $lieu_values = field_get_items('node',$eff,'field_lieu');
    // $lieu_values = $lieu_values ? $lieu_values : array();
    // // dsm($lieu_values, '$lieu_values');
    
    // $lieu = array();
    // foreach ($lieu_values as $value) {
    //   $term = taxonomy_term_load($value['tid']);
    //   $term = i18n_taxonomy_localize_terms($term);
    //   // dsm($term, '$term');
    //   $lieu[$term->tid] = array(
    //     'tid' => $term->tid,
    //     'name' => t($term->name),
    //   );
    // }
    
    # topologie
    // $topologie_values = field_get_items('node',$eff,'field_topologie');
    // // dsm($topologie_values, '$topologie_values');
    // $topologies = array();
    // if($topologie_values){
    //   foreach ($topologie_values as $value) {
    //     $term = taxonomy_term_load($value['tid']);
    //     $term = i18n_taxonomy_localize_terms($term);

    //     $topologies[$term->tid] = array(
    //       'tid' => $term->tid,
    //       'name' => $term->name,
    //     );
    //   }
    // }
    
    $perfadded = array();
    foreach ($eff->field_performances['und'] as $perf) {
      
      if(in_array($perf['target_id'], $perfadded))
        continue;
      
      $perfadded[] = $perf['target_id'];
      
      $perf = node_load($perf['target_id']);
      // $perf = entity_load('node', array($perf['target_id']), NULL, FALSE);
      // dsm($perf, '$perf');

      // $prefix = $language->language == 'fr' ? 'en/' : '';

      // $date = array(
      //   "nid"=>$perf->nid,
      //   "filters" => array(),
      //   'ajax_link'=> 'perfart/ajax/perf/'.$perf->nid,
      //   'node_link'=> drupal_get_path_alias('node/'.$perf->nid, $language->language),
      //   'node_translation'=> $prefix . drupal_get_path_alias('node/'.$perf->nid, $language->language == 'fr' ? 'en' : 'fr'),
      //   'perf_title'=>$perf->title,
      //   'language'=>$language,
      // );

      $node_path = drupal_get_path_alias('node/'.$perf->nid, $language->language);
      $node_link = l($debutMatches[1] .' | '. $perf->title,$node_path, array('html'=>true));


      # timeline content + concepteurs filter
      $content = '<div class="date" nid="'.$perf->nid.'" >';
      // $content .= '<div class="text-content">';
      $content .= '<h4>'.$node_link.'</h4>';

      #concepteur
      $concepteurs_values= field_get_items('node',$perf,'field_concepteur');
      $personnes = array();
      if($concepteurs_values){
        $concepteurs = array();
        foreach ($concepteurs_values as $concepteur) {
          // $concepteur_term = taxonomy_term_load($concepteur['tid']);
          try {
            $concepteur_term = taxonomy_term_load($concepteur['tid']);  
          } catch (Exception $e) {
            throw new Exception( 'taxonomy_term_load didn\'t', 0, $e);
            continue;
          }

          // dsm($concepteur_term);
          $concepteurs[] = $concepteur_term->name;
          // $personnes[$concepteur_term->tid] = array(
          //   "tid" => $concepteur_term->tid,
          //   "name" => $concepteur_term->name,
          // );
        }
        $content .= '<h5>'.implode(', ', $concepteurs).'</h5>';
      }
      
      #images
      if($images_values= field_get_items('node',$perf,'field_images')){
        //dsm($images_values, '$images_values');
        $image = theme('image_style', array(
          'style_name'=>'home_no_js', 
          'path'=>$images_values[0]['uri'],
        ));
        //$content .= $image;
        // dsm($image, 'image');
        $date['thumb'] = l($image, $node_path, array('html'=>true));
        $content .= $date['thumb'];
      }

      // $content .= '</div>';
      
      ## close content link
      $content .= '</div>';
      
      # timeline array with dates
      // $date += array(
      //   'content'=> $content,
      //   'start'=>array(
      //     'year'=>$debutMatches[1],
      //     'month'=>isset($debutMatches[2]) ? $debutMatches[2] : null,
      //     'day'=>isset($debutMatches[3]) ? $debutMatches[3] : null,
      //   ),
      // );
      
      
      # filter organisateur
      // $organisateur_values= field_get_items('node',$perf,'field_organisateur');
      // // dsm($organisateur_values, 'org');
      // if($organisateur_values){
      //   foreach ($organisateur_values as $personne) {
      //     $term = taxonomy_term_load($personne['tid']);
      //     // dsm($term);
      //     $personnes[$term->tid] = array(
      //       "tid" => $term->tid,
      //       "name" => $term->name,
      //     );
      //   }
      // }
      
      # filter participants
      // $participants_values= field_get_items('node',$perf,'field_participant');
      // // dsm(count($participants_values), 'part');
      // if($participants_values){
      //   foreach ($participants_values as $personne) {
      //     $term = taxonomy_term_load($personne['tid']);
      //     // dsm($term);
      //     $personnes[$term->tid] = array(
      //       "tid" => $term->tid,
      //       "name" => $term->name,
      //     );
      //   }
      // }
      
      
      # filter topologie flag
      // $date["filters"]['topologies'] = $topologies;
      
      # filter lieu flag      
      // $date['filters']['places'] = $lieu;
            
      # filter artistes
      // $date['filters']['peoples'] = $personnes;
      
      pager_default_initialize($count, $limit);

      // $data[] = $date;
      $list['items'][] = $content;
      
    }
  }

  // dsm($data, '$data');
  return theme('item_list', $list) . theme('pager');
}

/**
* perfart_search()
* ajax search
*
*/
function perfart_search(){
  $keys = rawurldecode($_GET['keys']);
  
  $return = array('keys' => $keys);

  $module = 'node';
  if (!empty($module)) {
    $active_module_info = search_get_info();
    if (isset($active_module_info[$module])) {
      $info = $active_module_info[$module];
    }
  }
  $return['info'] = $info;

  // $results = search_data($keys, $info['module'], $conditions);
  if($results = search_data($keys, $info['module'])){
    foreach ($results['#results'] as $result) {
      $return['results'][] = $result['node']->nid;
    }
  }

  drupal_json_output($return);
}

/**
* perfart_search_api()
* ajax search_api
*
*/
function perfart_search_api(){
  $typed = rawurldecode($_GET['typed']);
  
  preg_match_all('/\s?[^\s]+\s?/', $typed, $words);
  // dsm($words, "words");
  
  foreach ($words[0] as $word) {
    // dsm($word);
    $word = trim($word);
    // $word = str_replace($match, $replace, $word);
    // dsm($word, 'word');
    $keys[] = $word;
  }
  // dsm($keys, 'keys');

  global $language;

  $return = array('keys' => $keys);

  $index_machine_name = $language->language == 'fr' ? 'performances_fr' : 'performance_en';
  $index = search_api_index_load($index_machine_name);

  if ($keys) {
    $query = search_api_query($index_machine_name, array('conjunction'=>'OR', 'parse mode'=>'direct'))->keys(implode(' ', $keys));
    $results = $query->execute();
    $return['results'] = $index->loadItems(array_keys($results['results']));
  }

  drupal_json_output($return);
}


/**
* perfart_get_perf()
* get one perf through ajax
*
*/
function perfart_get_perf($nid = false){
  if($nid){
    global $language;
    //dsm($language, 'language');
    $node = node_load($nid);
    // dsm($node, '$node');
    
    $node_view = node_view($node, "gridready", $language->language);
    // dsm($node_view, '$node_view');
    
    $response = array(
      "node_view"=>render($node_view),
      "nid"=>$nid,
    );
    
    // dsm($response, '$response');
    // return 'debug mode of perfart_get_perf()';
    
    drupal_json_output($response);
    
    
  }else{
    return false;
  }
}

/**
*
* perfart_get_home()
*
*/
function perfart_get_home(){
  $return = array();
  global $language;
  $return['language'] = $language;
  
  $front = node_view(node_load(1), 'full', $language->language);
  // dsm($front, 'front');
  $frontrendered = drupal_render($front);
  $return['front'] = $frontrendered;
  // dsm($frontrendered, '$frontrendered');

  // return 'debug mode of perfart_get_home()';
  drupal_json_output($return);
}

/**
 * DEV
 * 
 */
function perfart_update_cer($page = 0){
  $itemsbypage = 100;
  $query = new EntityFieldQuery;
  $query
     ->entityCondition('entity_type', 'node')
     ->entityCondition('bundle', array('performance'))
     ->fieldCondition('field_effectuations', 'target_id', 'NULL', '!=')
     ->range($page*$itemsbypage, $itemsbypage);
      // ->propertyCondition('status', 1)

     // ->pager(100, 1);
     // ->propertyOrderBy('created', 'DESC');
  
  $result = $query->execute();
  // 
  $delta = 0;
  if(count($result['node'])){
    foreach ($result['node'] as $nid => $node) {
      $node = node_load($nid);
      // dsm($node);
    //    // module_invoke_all('entity_update', $node, 'node');
      corresponding_entity_references_processing_entity('update', $node, 'node');
      // node_save($node);
      $delta++;
    }
  }
  // dsm($delta);
  return $delta." nodes where updated.";
}

function perfart_clear_effectuations_perf_ref($page = 0){
  $itemsbypage = 100;
  $query = new EntityFieldQuery;
  $query
     ->entityCondition('entity_type', 'node')
     ->entityCondition('bundle', array('effectuation'))
     ->fieldCondition('field_performances', 'target_id', 'NULL', '!=')
     ->range($page*$itemsbypage, $itemsbypage);
      // ->propertyCondition('status', 1)

     // ->pager(100, 1);
     // ->propertyOrderBy('created', 'DESC');
  
  $result = $query->execute();
  // 
  $delta = 0;
  if(count($result['node'])){
    foreach ($result['node'] as $nid => $node) {
      $node = node_load($nid);
      // dsm($node);
      $node->field_performances = NULL;
    //    // module_invoke_all('entity_update', $node, 'node');
    //   corresponding_entity_references_processing_entity('update', $node, 'node');
      node_save($node);
      $delta++;
    }
  }
  // dsm($delta);
  return $delta." nodes where updated.";
}
