<?php

abstract class PerfBasicMigration extends PerfApiMigration {

	public function __construct(){
		
		$this->description = t('Migrate Performance Basic Class');
		
    parent::__construct();

    // There isn't a consistent way to automatically identify appropriate "fields"
    // from an XML feed, so we pass an explicit list of source fields
		$fields = array(
			'treeline_id' => t('Treeline id'),
			'title' => t('title'),
			'sous_titre' => t('Sous-titre'),
			'language' => t('Language'),
			'description' => t('description'),
			'auteur_description' => t('Auteur description'),
			'language_description' => t('Language description'),
			'intention' => t('Intention'),
			'auteur_intention' => t('Auteur intention'),
			'language_intention' => t('Language intention'),
			'serie' => t('Série'),
			'typologie_performance' => t('Typologie performance'),
			'tags_libre' => t('Tags libres'),
			'concepteur' => t('Concepteur'),
			'executant' => t('Executant'),
			'organisateur' => t('Organisateur'),
			'contexte_theorique' => t('contexte_theorique'),
			'auteur_contexte_theorique' => t('auteur_contexte_theorique'),
			'language_contexte_theorique' => t('Language contexte'),
      // 'date_de_debut' => t('Date de debut'),
      // 'date_de_fin' => t('Date de fin'),
      // 'lieu' => t('Lieu'),
      // 'duree' => t('Durée'),
      // 'topologie' => t('Topologie'),
      'effectuations_id' => t('effectuations id'),
			'temoin' => t('Temoin'),
			'site_internet' => t('Site internet'),
			'images' => t('Images'),
      'images_alt' => t('Images Alt'),
      'images_title' => t('Images Title'),
			'recherche' => t('recherche'),
			'sources_bibliographiques' => t('Sources bibliographiques'), // BIBLIOGRAPHIE
			'docs_audiovisuels' => t('docs audio visuel'), // DOC_AUDIOVISUEL
			'docs_sonor' => t('docs sonor'),//DOC_SONORE
			'documents' => t('documents'), // DOC_IMPRIME
			'objects' => t('Objets'), // OBJET
			
      //       'docs_press' => t('doc press'), // DOC_PRESSE
      // 'docs_manuscrit' => t('doc manuscrits'), // DOC_MANUSCRITS
    );
	
		// The source ID here is the one retrieved from the XML listing file, and
	  // used to identify the specific item's file
	  $this->map = new MigrateSQLMap($this->machineName,
	    array(
	      'treeline_id' => array(
	        'type' => 'varchar',
	        'length' => 255,
	        'not null' => TRUE,
	      )
	    ),
	    MigrateDestinationNode::getKeySchema()
	  );
  
		// This can also be an URL instead of a file path.
    $xml_folder = DRUPAL_ROOT . '/' . drupal_get_path('module', 'PerfMigrate') . '/xml/';
    $items_url = $xml_folder . 'baseperf-parsed.xml';

    // We use the MigrateSourceMultiItems class for any source where we obtain the list
    // of IDs to process and the data for each item from the same file. Typically the data
    // for an item is not contained in a single line within the source file. Examples include
    // multiple items defined in a single xml file or a single json file where in both cases
    // the id is part of the item.

    $item_ID_xpath = '@ID';         // relative to item_xpath and gets assembled
                                    // into full path /producers/producer/sourceid
    

    $items_class = new MigrateItemsXML($items_url, $this->item_xpath, $item_ID_xpath); // 
    $this->source = new MigrateSourceMultiItems($items_class, $fields);

    $this->destination = new MigrateDestinationNode('performance');
    
		$this->addFieldMapping('language')->defaultValue('fr');
		$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);
		
		# titre & sous titre
    // $this->addFieldMapping('title', 'title')
    //          ->xpath('@TITRE');
		
		$this->addFieldMapping('title_field', 'title');
    $this->addFieldMapping('title_field:language', 'language');
    
		$this->addFieldMapping('field_sous_titre', 'sous_titre')
         ->xpath('@SOUS_TITRE');
			
		# description
		$this->addFieldMapping('field_description', 'description');
		$this->addFieldMapping('field_description:format')->defaultValue('filtred_html');
		$this->addFieldMapping('field_description:language', 'language_description');
		$this->addFieldMapping('field_description:author', 'auteur_description');
		
		# intention (nexiste pas dans la base xml)
		$this->addFieldMapping('field_intention', 'intention');
		$this->addFieldMapping('field_intention:format')->defaultValue('filtred_html');
		$this->addFieldMapping('field_intention:language', 'language_intention');
		$this->addFieldMapping('field_intention:author', 'auteur_intention');

		# contexte theorique
    $this->addFieldMapping('field_contexte_theorique', 'contexte_theorique');
    $this->addFieldMapping('field_contexte_theorique:format')->defaultValue('filtred_html');
    $this->addFieldMapping('field_contexte_theorique:language', 'language_contexte_theorique');
    $this->addFieldMapping('field_contexte_theorique:author', 'auteur_contexte_theorique');
		
		# typologie perf
		$this->addFieldMapping('field_type_de_performance', 'typologie_performance')
				 ->xpath('TYPOLOGIE_PERFORMANCE/@TYPOLOGIE_PERFORMANCE');
		$this->addFieldMapping('field_type_de_performance:create_term')->defaultValue(TRUE);
		
		# serie
		$this->addFieldMapping('field_serie', 'serie')
				 ->xpath('SERIE/@NOM_SERIE');
		$this->addFieldMapping('field_serie:create_term')->defaultValue(TRUE);
		
		# tags libre perf
		$this->addFieldMapping('field_tags_libre', 'tags_libre');
		$this->addFieldMapping('field_tags_libre:create_term')->defaultValue(TRUE);
		
		# personnes
		$this->addFieldMapping('field_concepteur', 'concepteur');
		$this->addFieldMapping('field_concepteur:create_term')->defaultValue(TRUE);
		$this->addFieldMapping('field_executant', 'executant');
		$this->addFieldMapping('field_executant:create_term')->defaultValue(TRUE);
		$this->addFieldMapping('field_organisateur', 'organisateur');
		$this->addFieldMapping('field_organisateur:create_term')->defaultValue(TRUE);
		$this->addFieldMapping('field_temoin', 'temoin');
		$this->addFieldMapping('field_temoin:create_term')->defaultValue(TRUE);

		# lieu date contexte
    // $this->addFieldMapping('field_date_de_debut', 'date_de_debut');    
    // $this->addFieldMapping('field_date_de_fin', 'date_de_fin');
    // $this->addFieldMapping('field_dure', 'duree');   
    // $this->addFieldMapping('field_lieu', 'lieu')
    //     ->xpath('LIEU_DATE_CONTEXTE/@NOM_LIEU');
    // $this->addFieldMapping('field_lieu:create_term')->defaultValue(TRUE);
    // $this->addFieldMapping('field_topologie', 'topologie')
    //     ->xpath('LIEU_DATE_CONTEXTE/@TYPE');
    // $this->addFieldMapping('field_topologie:create_term')->defaultValue(TRUE);
		
		$this->addFieldMapping('field_effectuations', 'effectuations_id')
        ->sourceMigration('PerfLDCNode');
		
		#site internet
		$this->addFieldMapping('field_site_internet', 'site_internet');
		
		#images
		$this->addFieldMapping('field_images', 'images');
		$this->addFieldMapping('field_images:source_dir')->defaultValue('public://SRC_IMAGES');
		// $this->addFieldMapping('field_images:destination_file', 'images');
    // $this->addFieldMapping('field_images:alt', 'images_alt');
    $this->addFieldMapping('field_images:title', 'images_title');
    $this->addFieldMapping('field_images:alt', 'images_alt');
		
		$this->addFieldMapping('field_recherche', 'recherche')
		    ->xpath('/RECHERCHE/@NOTES');
		
		$this->addFieldMapping('field_sources_bibliographiques', 'sources_bibliographiques')
		    ->xpath('/BIBLIOGRAPHIE/@BIBLIOGRAPHIE');

    $this->addFieldMapping('field_documents_videos', 'docs_audiovisuels')
            ->sourceMigration('PerfDvidsNode');

    $this->addFieldMapping('field_documents_sonor', 'docs_sonor')
            ->sourceMigration('PerfDsonsNode');

		$this->addFieldMapping('field_documents', 'documents')
        ->sourceMigration(array('PerfDimpNode', 'PerfDpressNode', 'PerfDmanuNode')); // ?????

    $this->addFieldMapping('field_objects', 'objects')
            ->sourceMigration('PerfObjetNode');

		
		$this->addUnmigratedDestinations(array('revision_uid', 'created', 'changed', 'revision', 'log', 'tnid','comment', 'uid','path', 'pathauto',
		  'title',
		  'title_field:format',
			'field_sous_titre:format', 'field_sous_titre:language',
			'field_performances_associees',
      // 'body:summary',
      // 'field_auteur_description:source_type',
      // 'field_auteur_intention:source_type',
      // 'field_auteur_contexte:source_type',
			'field_serie:source_type', 'field_type_de_performance:source_type', 'field_tags_libre:source_type',
			'field_concepteur:source_type','field_executant:source_type','field_organisateur:source_type','field_temoin:source_type',
      // 'field_date_de_debut:format', 'field_date_de_debut:language', 'field_date_de_fin:format', 'field_date_de_fin:language',
      // 'field_dure:format', 'field_dure:language',
      // 'field_lieu:source_type', 'field_topologie:source_type'
      'field_images:file_class', 'field_images:language', 'field_images:destination_dir', 'field_images:destination_file', 'field_images:file_replace', 'field_images:preserve_files',
      'field_recherche:language', 'field_recherche:format',
      'field_sources_bibliographiques:language', 'field_sources_bibliographiques:format',
      //'field_images:alt', //'field_images:title',
		));
    
	}
	
	public function prepareRow($row){
		// dsm($row , '--- $row ---');
		$xml = $row->xml;
		
    $row->language = 		array('fr', 'en');
		
		$titre = $this->getAttribute($xml, 'TITRE');
		$traduction_titre = $this->getAttribute($xml, 'TRADUCTION_TITRE');
		$traduction_titre = $traduction_titre != '' ? $traduction_titre : $titre;
		$row->title = array(
		  $titre,
      $traduction_titre,
		);

		# description
    $results = $this->getTextsAuthors($xml->xpath('DESCRIPTION'), 'DESCRIPTION', $row->language);
    $row->description = $results['values'];
    $row->auteur_description = $results['authors'];
    $row->language_description = $results['language'];

		# intention
		$results = $this->getTextsAuthors($xml->xpath('INTENTION'), 'INTENTION', $row->language);
    $row->intention = $results['values'];
    $row->auteur_intention = $results['authors'];
    $row->language_intention = $results['language'];

		# Contexte theorique
		$results = $this->getTextsAuthors($xml->xpath('CONTEXTE_THEORIQUE'), 'CONTEXTE_THEORIQUE', $row->language);
    $row->contexte_theorique = $results['values'];
    $row->auteur_contexte_theorique = $results['authors'];
    $row->language_contexte_theorique = $results['language'];
		
		#tags libres
		$tags = array();
		foreach ($xml->xpath('MOTS_CLE') as $xml_mot_clef)
			$tags[] = $this->getAttribute($xml_mot_clef, 'MOT_CLE');
		$row->tags_libre = $tags;
		
		# personnes
		$concepteurs = array();
		foreach ($xml->xpath('PERSONNE[@CONCEPTEUR="oui"]') as $xml_concepteur)
			$concepteurs[] = $this->getPersonne($xml_concepteur);
		$row->concepteur = $concepteurs;

		$executants = array();
		foreach ($xml->xpath('PERSONNE[@EXECUTANT="oui"]') as $xml_executant)
			$executants[] = $this->getPersonne($xml_executant);
		$row->executant = $executants;

		$organisateurs = array();
		foreach ($xml->xpath('PERSONNE[@ORGANISATEUR="oui"]') as $xml_organisateur)
			$organisateurs[] = $this->getPersonne($xml_organisateur);
		$row->organisateur = $organisateurs;
		
		$temoins = array();
		foreach ($xml->xpath('TEMOIN') as $xml_temoin)
			$temoins[] = $this->getPersonne($xml_temoin, '_TEMOIN');
		$row->temoin = $temoins;
		
		# lieu date contexte
    // $ldc = $xml->LIEU_DATE_CONTEXTE;
    // $row->date_de_debut = $this->getDate($ldc, 'DEBUT');
    // $row->date_de_fin = $this->getDate($ldc, 'FIN');
    // $row->duree = $this->getAttribute($ldc, 'DUREE') .' '. $this->getAttribute($ldc, 'UNITE_DUREE');
    // $row->lieu = $this->getAttribute($ldc, 'NOM_LIEU');
		$effectuations_id = array();
		foreach ($xml->xpath('LIEU_DATE_CONTEXTE') as $ldc)
			$effectuations_id[] = $this->getAttribute($ldc, 'ID');
		$row->effectuations_id = count($effectuations_id) ? $effectuations_id : NULL;

    # doc audiovisuel
		$docs = array();
		foreach ($xml->xpath('DOC_AUDIOVISUEL') as $doc)
			$docs[] = $this->getAttribute($doc, 'ID');
		$row->docs_audiovisuels = count($docs) ? $docs : NULL;

    # doc sonor
		$docs = array();
		foreach ($xml->xpath('DOC_SONORE') as $doc)
			$docs[] = $this->getAttribute($doc, 'ID');
		$row->docs_sonor = count($docs) ? $docs : NULL;

    # doc imprime
		$docs = array();
		foreach ($xml->xpath('DOC_IMPRIME') as $doc)
			$docs[] = $this->getAttribute($doc, 'ID');

		foreach ($xml->xpath('DOC_PRESSE') as $doc)
			$docs[] = $this->getAttribute($doc, 'ID');

		foreach ($xml->xpath('DOC_MANUSCRITS') as $doc)
			$docs[] = $this->getAttribute($doc, 'ID');
  		
		$row->documents = count($docs) ? $docs : NULL;

    # objet
		$docs = array();
		foreach ($xml->xpath('OBJET') as $doc)
			$docs[] = $this->getAttribute($doc, 'ID');
		$row->objects = count($docs) ? $docs : NULL;

    
		#site internet
		// $sites = array();
		// foreach ($xml->xpath('SITE_INTERNET') as $xml)
		// 	$sites[] = str_replace('http://', '', $this->getAttribute($xml, 'URL'));
		// $row->site_internet = $sites;
		// dsm($row->site_internet)

		/*
			TODO site internet ne marche pas !!!
		*/
    // $row->site_internet = '';
		foreach ($xml->xpath('SITE_INTERNET') as $xml_site)
			//$row->site_internet = array('url'=>str_replace('http://', '', $this->getAttribute($xml_site, 'URL')));
			$row->site_internet = str_replace('http://', '', $this->getAttribute($xml_site, 'URL'));
    // dsm($row->site_internet, '$row->site_internet');
    // drush_log(dt('web : !url', array('!url'=>$row->site_internet)), 'status');
		
		
		#images
		$images = array();
    $titles = array();
    $alts = array();
    // $i = 0;
    $str_xml = print_r($xml, true);
    //drush_log(dt('xml : !xml', array('!xml'=>$str_xml)), 'status');
    //drush_log(dt('start images import : !images', array('!images'=>count($xml->IMAGE_CONSULTABLE))), 'status');
    foreach ($xml->IMAGE_CONSULTABLE as $xml_image) { //IMAGE_CONSULTABLE
      // drush_log(dt('image'), 'status');
			$images[] = $this->getAttribute($xml_image, 'SRC');
      $alts[] = $this->getAttribute($xml_image, 'ALT');
      $titles[] = $this->getAttribute($xml_image, 'TITLE');
      // $i++;
		}
		$row->images = $images;
    $row->images_title = $titles;
    $row->images_alt = $alts;
    // dsm($row->images, '$row->images');
	}
	
	public function prepare($node, stdClass $row) {
	  $node->name = 'migration';
	  $node->workflow = 2;
		
  }

  public function complete($node, stdClass $row){
    $handler = entity_translation_get_handler('node', $node);

    $translation = array(
      'translate' => 0,
      'status' => 1,
      'language' => 'en',
      'source' => $node->language,
    );

    $handler->setTranslation($translation, $node);

    node_save($node);
  }
	
}
