<?php
/**
 * MaterioMateriauNodeMigration
 * 
 */
class MaterioBrevesNodeMigration extends MaterioBasicMigration {
  public function __construct() {
    parent::__construct();
    $this->description = t('Migrate Materio Materiau nodes');

		// provide better description for source fields
		// and add new field source not from sql
    $source_fields = array(
    	'titlefield'=>t('title field'),
			'languages'=> t('languages'),
			'memo' => t('memo'),
			'images'=>t('images'),
			'images_titles'=>t('images titles'),
			'images_alts'=>t('images alts'),
			// 'source'=>t("source"),
			// 'materiau'=>t('materiau ref'),
			'video'=>t('video'),
    );
		
		$query = db_select(MIG_MAT_SRC_DB_D6 .'.fr_i18n_node', 'i');
		
		$query->join(MIG_MAT_SRC_DB_D6 .'.fr_node', 'n', 'n.nid = i.nid');
		$query->join(MIG_MAT_SRC_DB_D6 .'.fr_node_revisions', 'nr', 'nr.nid = n.nid');
		// $query->join(MIG_MAT_SRC_DB_D6 .'.fr_content_field_imago', 'im', 'im.nid = n.nid');
		
		$query
				->condition('i.status', "0", "=")
				->condition('n.type',"actu")
				->fields('i', array('trid'))
				->fields('n', array('nid', 'status', 'promote', 'sticky', 'created', 'changed', 'language', 'tnid'))
				->fields('nr', array('title', 'body', 'teaser', 'format'));
				// ->fields('im', array('title', 'body', 'teaser', 'format'));
		
		// print  "\n\n- - - - - - \n\n";
		// print_r($query->__toString());
		// print  "\n\n- - - - - - \n\n";


		$this->source = new MigrateSourceSQL($query, $source_fields);
	  $this->destination = new MigrateDestinationNode('breve');
  
	  $this->map = new MigrateSQLMap($this->machineName,
	    array(
	      'nid' => array(
	        'type' => 'int',
	        'unsigned' => TRUE,
	        'not null' => TRUE,
	        'description' => 'OLD Unique Materiau NID',
	        'alias' => 'i',
	      )
	    ),
	    MigrateDestinationNode::getKeySchema()
	  );

		$this->addFieldMapping('is_new')->defaultValue(TRUE);
		
		$this->addSimpleMappings(array('created', 'changed', 'status', 'promote', 'sticky', 'language', 'title'));

		$this->addFieldMapping('field_memo', 'memo');
	
		$this->addFieldMapping('title_field', 'titlefield');
		$this->addFieldMapping('title_field:language', 'languages');
	
		$this->addFieldMapping('body', 'body');
		$this->addFieldMapping('body:language', 'languages');
		$this->addFieldMapping('body:format')->defaultValue('filtred_html');


		$this->addFieldMapping('field_visuel', 'images');
		$this->addFieldMapping('field_visuel:source_dir')->defaultValue('public://SRC_imago');
		$this->addFieldMapping('field_visuel:title', 'images_titles');
		$this->addFieldMapping('field_visuel:alt', 'images_alts');

		$this->addFieldMapping('field_video_filter', 'video');

		// $this->addFieldMapping('field_tags_libres', 'tags');
		// $this->addFieldMapping('field_tags_libres:create_term')->defaultValue(TRUE);

		$this->addUnmigratedDestinations(array('revision', 'revision_uid', 'log', 'tnid', 'comment', 'uid', 'path', 'pathauto',
			'title_field:format',
			'body:summary',
			'field_source', 
			// 'field_video_filter',
			'field_materiau_ref',
			'field_memo:format', 'field_memo:language',
			'field_onthologie', 'field_onthologie:source_type', 'field_onthologie:create_term',
			'field_visuel:file_class','field_visuel:language','field_visuel:destination_dir','field_visuel:destination_file','field_visuel:file_replace','field_visuel:preserve_files',
			'field_tags_libres', 'field_tags_libres:source_type', 'field_tags_libres:create_term',
		));

	}
	
	public function prepareRow($cr){
		// dsm($cr);
		// print "\n- - - - - - - - \n";
		// print $cr->nid . "\n";
		// print $cr->title . "\n";		

		$body = $cr->body;
		
		$cr->memo = '';

		if($cr->trid){
			$query = db_select(MIG_MAT_SRC_DB_D6 .'.fr_i18n_node', 'i');
		
			$query->join(MIG_MAT_SRC_DB_D6 .'.fr_node', 'n', 'n.nid = i.nid');
			$query->join(MIG_MAT_SRC_DB_D6 .'.fr_node_revisions', 'nr', 'nr.nid = n.nid');

			$query
				->condition('i.status', "0", "<>")
				->condition('i.trid', $cr->trid, "=")
				->fields('i', array('trid'))
				->fields('n', array('nid', 'status', 'promote', 'sticky', 'created', 'changed', 'language', 'tnid'))
				->fields('nr', array('title', 'body', 'teaser', 'format'));

			$result = $query->execute();

			foreach ($result as $record) {
				$tr = $record;
			}

			// print $cr->title . "\n";
			// print $tr->title . "\n";

			$cr->titlefield = array($cr->title, $tr->title);

			$cr->body = array($cr->body, $tr->body);
			// $cr->teaser = array($cr->teaser, $cr->tnr_teaser);

			$cr->languages = array($cr->language, $tr->language);
		}else{
			$cr->languages = $cr->language;
			$cr->titlefield = $cr->title;
			// $cr->teaser = htmlspecialchars_decode($cr->teaser);
		}
		
		/* IMAGES */
		$query = db_select(MIG_MAT_SRC_DB_D6.'.fr_content_field_imago', 'im');
		$query->join(MIG_MAT_SRC_DB_D6.'.fr_files', 'f', 'f.fid = im.field_imago_fid');
		$query
			->condition('im.nid', $cr->nid, "=")
			// ->condition('f.fid', $cr->nid, "=")
			->fields('im', array('field_imago_list', 'field_imago_data'))
			->fields('f', array('filename'));

		$images = $query->execute();
		$cr->images = array();
		$cr->images_titles = array();
		$cr->images_alts = array();

		foreach ($images as $image) {
			// print_r($image);
			$cr->images[] = $image->filename;
			$data = unserialize($image->field_imago_data);
			$cr->images_alts[] = $data['alt'];
			$cr->images_titles[] = $data['title'];
		}

		
		/* source */
		//Source : <a href="http://ucsdnews.ucsd.edu/pressreleases/researchers_create_living_neon_signs_composed_of_millions_of_glowing_bacter/" target="_blank">UCSanDiego</a>
		// preg_match('/Source\s:\s<a\shref="([^"]*)"[^>]*>([^<]*)<\/a>/', $body, $matches);
		// if(count($matches)){
		// 	print_r($matches);
		// 	$cr->source = str_replace('http://', '', $matches[1]);
		// }

		/* materio */
		// (mat&eacute;riO P0059)
		preg_match('/\(mat&eacute;riO\s([^\)]*)\)/', $body, $matches);
		if(count($matches)){
			// print_r($matches);
			$cr->memo .= "ref materio : ".$matches[1]."\n";
		}
		
		/* video */
		//[video:http://www.youtube.com/watch?v=3Fzu2Av6BmE align:center autoplay:1]
		preg_match('/\[video:([^\s]*)[^\]]*]/', $body, $matches);
		if(count($matches)){
			// print_r($matches);
			$cr->video = $matches[1];
		}


		$query = db_select(MIG_MAT_SRC_DB_D6 .'.fr_term_node', 'tn');
		$query->join(MIG_MAT_SRC_DB_D6 .'.fr_term_data', 'td', 'td.tid = tn.tid');

		$query
			->condition('tn.nid', $cr->nid, "=")
			->fields('td', array('name'));

		$result = $query->execute();
		$terms = array();
		foreach ($result as $record) {
			$terms[] = $record->name;
		}
		$cr->memo .= 'terms : '.implode(', ', $terms)."\n";



		return TRUE;
	}
	
	
	public function prepare($node, stdClass $row) {
		// dsm('-- prepare --');
		// dsm($node, '$node');
		// dsm($row, '$row');
		
	  $node->workflow = 4;
		
  }
	
	// public function complete($node, $row) {
	// 	// dsm('-- complete --');
	// 	//     // Do what you need to do to 
	// 	// dsm($row, '$row');
	// 	// dsm($node, '$node');
	// 
	//   }
	
	
	
}