<?php

/**
 * Implement hook_menu
 */
function policia_migracion_menu() {
	$items['migracion_descargables'] = array(
    'page callback' => 'policia_migracion_descargables_callback',
    'access arguments' => array('access content'),
  );
  $items['migracion_noticias'] = array(
    'page callback' => 'policia_migracion_noticias_callback',
    'access arguments' => array('access content'),
  );
  return $items;
}

function policia_migracion_descargables_callback(){
  return drupal_get_form('policia_migracion_form');
}

function policia_migracion_noticias_callback(){
  return drupal_get_form('policia_migracion_noticias_form');
}

function policia_migracion_noticias_form($node, &$form_state){
  $directorio=opendir(drupal_realpath('public://policia_xml/'));
  $items = array();
  while ($archivo = readdir($directorio))
  {
    if(!is_dir($archivo))
    {
      $items[$archivo] = $archivo;
    }
  }
  $form['selected'] = array(
   '#type' => 'select',
   '#title' => t('Selected'),
   '#options' => $items,
   '#description' => t('Seleccione el archivo que desea migrar'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

function extraerSRC($cadena) {
    preg_match('@src="([^"]+)"@', $cadena, $array);
    $src = array_pop($array);
    return $src;
}

function extraerHREF($cadena) {
    preg_match('@href="([^"]+)"@', $cadena, $array);
    $src = array_pop($array);
    return $src;
}

function policia_migracion_noticias_form_submit($form, &$form_state){
  if($form_state['values']['selected']){
    $file = simplexml_load_file("public://policia_xml/" . $form_state['values']['selected']) or die("Error: Cannot create object");
    $record = array();
    foreach ($file->children() as $value) {
      switch ((string) $value->nvarchar3) {
        case 'NARCOTRAFICO':
          $tid = 5;
          break;
        case 'OPERATIVIDAD':
          $tid = 4;
          break;
        case 'COMUNITARIAS':
          $tid = 2;
          break;
        case 'AMBIENTAL':
          $tid = 1;
          break;
        default:
          $tid = NULL;
          break;
      }
      if($tid){
        $entradilla = (string) $value->nvarchar4;
      }else{
        switch ((string) $value->nvarchar4) {
          case 'NARCOTRAFICO':
            $tid = 5;
            break;
          case 'OPERATIVIDAD':
            $tid = 4;
            break;
          case 'COMUNITARIAS':
            $tid = 2;
            break;
          case 'AMBIENTAL':
            $tid = 1;
            break;
          default:
            $tid = NULL;
            break;
        }
        $entradilla = (string) $value->nvarchar3;
      }
      if($tid){
        $src = extraerSRC((string) $value->ntext3);
        if(!$src){
          if(preg_match('/jpg/i', (string) $value->nvarchar5) || preg_match('/jpeg/i', (string) $value->nvarchar5)  || preg_match('/png/i', (string) $value->nvarchar5)){
            $src = (string) $value->nvarchar5;
          }
        }
        if(!$src){
          if(preg_match('/jpg/i', (string) $value->nvarchar6) || preg_match('/jpeg/i', (string) $value->nvarchar6)  || preg_match('/png/i', (string) $value->nvarchar6)){
            $src = (string) $value->nvarchar6;
          }
        }
        if($src){
          $unidad = (string) $value->nvarchar8;
          if(preg_match("/[0-9]/", (string) $value->nvarchar8)){
            $unidad = (string) $value->nvarchar9;
          }
          $record[] = array(
            'titulo' => (string) $value->nvarchar1,
            'fecha' => (string) $value->datetime2,
            'entradilla' => $entradilla,
            'content' => strip_tags(html_entity_decode((string) $value->ntext2)),
            'image' => $src,
            'evidencia' => extraerHREF((string) $value->ntext4),
            'unidad' => $unidad,
            'seccion' => $tid,
          );
        }
      }
    }
    $limit = 1;
    $chunks_data = array_chunk($record, $limit);
    $operations = array();
    foreach ($chunks_data as $chunk_data) {
      $operations[] = array('_policia_migracion_noticia_batch', $chunk_data);
    }
    $batch = array(
        'operations' => $operations,
        'finished' => '_policia_migracion_batch_finished',
        'title' => 'Migracion noticias iniciada ...',
    );
    batch_set($batch);
    batch_process('migracion_noticias');

  }
}

function policia_migracion_form($node, &$form_state){
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#submit' => array('policia_migracion_form_submit'),
  );
  return $form;
}

function policia_migracion_form_submit($form, &$form_state){
  $prepare = 'public://noticias/';
  if (file_prepare_directory($prepare, FILE_CREATE_DIRECTORY)) {
    $result = db_query("SELECT tth.parent, ttd.tid, ef.entityform_id from taxonomy_term_hierarchy tth inner join taxonomy_term_data ttd on tth.tid = ttd.tid inner join field_data_field_categoria fdc on ttd.tid = fdc.field_categoria_tid and fdc.bundle = 'descargable' inner join entityform ef on fdc.entity_id = ef.entityform_id and ef.type = 'descargable' order by tth.parent, ttd.tid, ef.entityform_id");
    $record = array();
    foreach ($result as $key => $value) {
      if($value->parent){
        $record[$value->parent][$value->tid]['parent'] = $value->parent;
        $record[$value->parent][$value->tid][] = $value->entityform_id;
      }else{
        $record[$value->tid]['parent'] = $value->tid;
        $record[$value->tid]['value'][] = $value->entityform_id;
      }
    }
    foreach ($record as $rkey => $rvalue) {
      $validador = FALSE;
      foreach ($rvalue as $rekey => $revalue) {
        if(is_numeric($rekey)){
          $validador = TRUE;
        }
      }
      if($validador){
        unset($record[$rkey]['value']);
      }
    }
    $limit = 1;
    $chunks_data = array_chunk($record, $limit);
    $operations = array();
    foreach ($chunks_data as $chunk_data) {
      $operations[] = array('_policia_migracion_batch', $chunk_data);
    }
    $batch = array(
        'operations' => $operations,
        'finished' => '_policia_migracion_batch_finished',
        'title' => 'Migracion iniciada ...',
    );
    batch_set($batch);
    batch_process('migracion_descargables');
  }
}

function _policia_migracion_noticia_batch($record, &$context){
  $result = db_query('SELECT n.title FROM node n INNER JOIN field_data_field_resumen fdfr ON n.nid = fdfr.entity_id WHERE n.title = :title OR fdfr.field_resumen_value = :resumen', array('title' => $record['titulo'], 'resumen' => $record['entradilla']));
  $result_title = $result->fetchAssoc();
  if(!isset($result_title['title'])){
    $explode = explode('/', $record['image']);
    $rawurlencode = array();
    foreach ($explode as $key => $value) {
      $rawurlencode[] = rawurlencode(urldecode($value));
    }
    $implode = implode('/', $rawurlencode);
    $url_imagen = 'http://portal.policia.gov.co' . $implode;
    $file = system_retrieve_file($url_imagen, 'public://noticias', TRUE, FILE_EXISTS_RENAME);
    if($file){
      $node = new stdClass();
      $node->type = 'noticias';
      node_object_prepare($node);
      $node->title = $record['titulo'];
      $node->language = LANGUAGE_NONE;
      $node->status = 1;
      $node->uid = 1;
      $date = explode('T', $record['fecha']);
      $fecha = strtotime(str_replace('/', '-',$date[0]));
      $node->created = $fecha;
      $node->changed = $fecha;
      $node->field_fecha_de_publicacion[LANGUAGE_NONE][0]['value'] = $date[0] . ' 00:00:00';
      $node->field_resumen[LANGUAGE_NONE][0]['value'] = $record['entradilla'];
      $node->body[LANGUAGE_NONE][0]['value'] = $record['content'];
      $name = basename($record['image']);
      $name = urldecode($name);
      $name = explode('.', $name);
      $saved_image = (array) $file;
      $saved_image['alt'] = $name[0];
      $saved_image['title'] = $name[0];
      $node->field_imagen_noticia[LANGUAGE_NONE][] = $saved_image;
      $node->field_seccion[LANGUAGE_NONE][0]['tid'] = $record['seccion'];

      $url_evidencia = 'public://evidencias/' . urldecode(basename($record['evidencia']));
      if(file_exists($url_evidencia)){
        $node->field_evidencia_noticia[LANGUAGE_NONE] = array();
        $file = (object) array(
          'uid' => 1,
          'uri' => $url_evidencia,
          'filemime' => file_get_mimetype($url_evidencia),
          'status' => 1,
          'display' => 1,
        );
        $prepare = 'private://noticias/evidencias/';
        if (file_prepare_directory($prepare, FILE_CREATE_DIRECTORY)) {
          $file = file_copy($file, $prepare . '/' . urldecode(basename($record['evidencia'])));
          $node->field_evidencia_noticia[LANGUAGE_NONE][0] = (array)$file;
        }       
      }
      $result_unidad = db_query("SELECT entity_id from field_data_field_siglas where bundle = 'unidades' and field_siglas_value = :siglas", array('siglas' => $record['unidad']));
      $result_unidad = $result_unidad->fetchAssoc();
      if($result_unidad['entity_id']){
        $node->field_unidad[LANGUAGE_NONE][0]['target_id'] = $result_unidad['entity_id'];
      }
      node_save($node);
      workbench_moderation_moderate($node, 'published');
    }
  }
}


function _policia_migracion_batch($record, &$context){
  $termino_principal = taxonomy_term_load($record['parent']);
  // Create node
  $node = new stdClass();
  $node->type = 'descargable';
  node_object_prepare($node);
  $node->title = $termino_principal->name;
  $node->language = LANGUAGE_NONE;
  $node->status = 1;
  $node->uid = 1;
  if(isset($record['value'])){
    // Create and save field collection for node
    $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_descargables'));
    $field_collection_item->setHostEntity('node', $node);
    $archivos = array();
    foreach ($record['value'] as $key => $value) {
      $entity = entity_load_single('entityform', $value);
      $entity->field_archivo['und'][0]['description'] = $entity->field_title['und'][0]['value'];
      $archivos[] = $entity->field_archivo['und'][0];
    }
    $field_collection_item->field_multiple_archivo['und'] = $archivos;
    $field_collection_item->save();
  }else{
    foreach ($record as $rkey => $rvalue) {
      if(is_numeric($rkey)){
        $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_descargables'));
        $field_collection_item->setHostEntity('node', $node);
          $archivos = array();
          foreach ($rvalue as $ikey => $ivalue) {
            if(is_numeric($ikey)){
              $entity = entity_load_single('entityform', $ivalue);
              $entity->field_archivo['und'][0]['description'] = $entity->field_title['und'][0]['value'];
              $archivos[] = $entity->field_archivo['und'][0];
            }
          }
        $field_collection_item->field_multiple_archivo['und'] = $archivos;
        $field_collection_item->save();
        $termino_secundario = taxonomy_term_load($rkey);
        $field_collection_item->field_title['und'][0]['value'] = $termino_secundario->name;
        $field_collection_item->save();
      }
    }
  }
 node_save($node);
}

/**
 *
 * @param unknown $success
 * @param unknown $results
 * @param unknown $operations
 */
function _policia_migracion_batch_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message(t('Datos actualizados.'));
  }
  else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array(
    '@operation' => $error_operation[0],
    '@args' => print_r($error_operation[0], TRUE),
    )));
  }
}