<?php
/**
 * MaterioMateriauNodeMigration
 * 
 */
class MaterioMateriauNodeMigration 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(
      'id_product' => t('Materiau id from source'),
			'company_fab'=>t('company_fab'),
			'company_distrib'=>t('company_distrib'),
			'title'=>t('title'),
			'name'=> t('en-fr name implemented on prepare'),
			'description'=> t('en-fr description implemented on prepare'),
			'nature'=> t('en-fr nature implemented on prepare'),
			'language'=> t('en-fr langauge description, used in prepare'),
			'family' => '',
			'localisation' => '',
			'identifiant' => '',
    );
		
		$query = db_select(MIG_MAT_SRC_DB .'.product_id', 'pid');
	
		$query->join(MIG_MAT_SRC_DB .'.product_industrial', 'pind', 'pind.id_product = pid.id_product');
		
		$query
				->fields('pid', array('id_product', 'id_materio', 'status', 'memo', 'source', 'date_creation', 'date_modif'))
				->fields('pind', array('id_industrial', 'quarity'));
		
		$query->addExpression('GROUP_CONCAT(DISTINCT pind.id_industrial)','list_industrial');
		$query->addExpression('GROUP_CONCAT(pind.quarity)','list_quarity');
		
		$query
			->orderBy('pid.id_product', 'DESC')
			->groupBy('pid.id_product');
	
		$this->source = new MigrateSourceSQL($query, $source_fields);
	  $this->destination = new MigrateDestinationNode('materiau');
  
	  $this->map = new MigrateSQLMap($this->machineName,
	    array(
	      'id_product' => array(
	        'type' => 'int',
	        'unsigned' => TRUE,
	        'not null' => TRUE,
	        'description' => 'OLD Unique Materiau ID',
	        'alias' => 'pid',
	      )
	    ),
	    MigrateDestinationNode::getKeySchema()
	  );

		$this->addFieldMapping('is_new')->defaultValue(TRUE);
		$this->addFieldMapping('created', 'date_creation');
		$this->addFieldMapping('changed', 'date_modif');
		$this->addFieldMapping('status')->defaultValue(1);
		$this->addFieldMapping('promote')->defaultValue(0);
		$this->addFieldMapping('sticky')->defaultValue(0);
		$this->addFieldMapping('language')->defaultValue('en');

		$this->addFieldMapping('title', 'title');
		$this->addFieldMapping('field_memo', 'memo');
	
		$this->addFieldMapping('title_field', 'name');
		$this->addFieldMapping('title_field:language', 'language');
	
		$this->addFieldMapping('field_description', 'description');
		$this->addFieldMapping('field_description:language', 'language');		
		$this->addFieldMapping('field_description:format')->defaultValue('filtred_html');
		
		$this->addFieldMapping('field_nature_titre', 'nature');
		$this->addFieldMapping('field_nature_titre:language', 'language');	
	
		$this->addFieldMapping('field_company_fab', 'company_fab');
		$this->addFieldMapping('field_company_fab:create_term')->defaultValue(false);
		$this->addFieldMapping('field_company_distrib', 'company_distrib');
		$this->addFieldMapping('field_company_distrib:create_term')->defaultValue(false);
	
		$this->addFieldMapping('pathauto')->defaultValue(1);
		$this->addFieldMapping('comment')->defaultValue(0);
		$this->addFieldMapping('revision')->defaultValue(0);
		
		$this->addFieldMapping(null, 'id_industrial');
		$this->addFieldMapping(null, 'quarity');
	
		$this->addFieldMapping('field_onthologie')->defaultValue(null);
		
		$this->addFieldMapping('field_famille', 'family');
		$this->addFieldMapping('field_localisation', 'localisation');
		$this->addFieldMapping('field_identifiant', 'identifiant');


	}
	
	public function prepareRow($cr){
		// dsm($cr);
		
		# get product infos FR
		$infos_fr = db_select(MIG_MAT_SRC_DB .'.product_info', 'pif_fr')
			->condition('pif_fr.id_locale', 2)
			->condition('pif_fr.id_product', $cr->id_product)
			->fields('pif_fr' , array('name', 'nature', 'description', 'technical', 'keywords'))//, 'usage'
			->distinct()->execute();

		foreach ($infos_fr as $record)
			$infos['fr'] = $record;
		
		if($infos['fr']->technical != '')
			$infos['fr']->description .= "<br />technical : ".$infos['fr']->technical; // . "<br />usage".$infos['fr']->usage

		# get product infos EN
		$infos_en = db_select(MIG_MAT_SRC_DB .'.product_info', 'pif_en')
			->condition('pif_en.id_locale', 1)
			->condition('pif_en.id_product', $cr->id_product)
			->fields('pif_en' , array('name', 'nature', 'description', 'technical', 'keywords'))//, 'usage' , 'keywords'
			->distinct()->execute();

		foreach ($infos_en as $record)
			$infos['en'] = $record;
		
		if($infos['en']->technical != '')
			$infos['en']->description .= "<br />technical : ".$infos['en']->technical; // . "<br />usage".$infos['en']->usage
		
		# set product infos
		$cr->title = 				$infos['fr']->name;
		$cr->name = 				array($infos['en']->name, $infos['fr']->name);
		$cr->description = 	array($infos['en']->description, $infos['fr']->description);
		$cr->nature = 			array($infos['en']->nature, $infos['fr']->nature);
		$cr->language = 		array('en', 'fr');

		# record keywords on memo
		$cr->memo .= ($cr->memo != '' ? "\n\n" : '') . $infos['fr']->keywords;
		
		# parse companies
		// dsm($cr->list_industrial, '-- $cr->list_industrial');
		// dsm($cr->list_quarity, '$cr->list_quarity');
		$industrials = explode(',', $cr->list_industrial);
		$quarities = explode(',', $cr->list_quarity);
		
		$companies_fab = array();
		$companies_distrib = array();
		
		$l = count($industrials);
		for ($i=0; $i < $l; $i++) { 
			$result = db_select(MIG_MAT_SRC_DB .'.industrial_info', 'iif')
				->fields('iif', array('id_industrial', 'company'))
				->condition('iif.id_industrial', $industrials[$i])
				->distinct()->execute();
				
			foreach ($result as $record) {
				// dsm($record);
				$company = trim($record->company);
				if(count(taxonomy_get_term_by_name($company.'-'.$record->id_industrial)))
					$company .= '-'.$record->id_industrial;	
				
				if($quarities[$i] == 'M'){
					$companies_fab[] = $company;
				}else{
					$companies_distrib[] = $company;
				}
			}
			
		}
		$cr->company_fab = implode(',', $companies_fab);
		$cr->company_distrib = implode(',', $companies_distrib);
		

		preg_match('/^(\w)([^-]+)-(\d+)$/', $cr->id_materio, $matches);
		// dsm($matches);
		$cr->family = $matches[1];
		$cr->localisation = $matches[2];
		$cr->identifiant = $matches[3];

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