<?php

/**
 * @file
 * A drush script that imports/updates migrated pages.
 */

require_once(__DIR__ . "/vendor/autoload.php");

use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;
use PHPHtmlParser\Dom;

// conversion from external terms to internal terms
$nav_terms = []; // not used

// This is the csv file holdings the list of incoming legacy URLs.
// @see README.md
$source_urls_csv = dirname(__FILE__) . '/../source_urls.csv';

$translations_map = dirname(__FILE__) . '/../translations_map.csv';
$fp = fopen($translations_map, 'w+');
$translations = [];

$wget_urls = dirname(__FILE__) . '/../wget_urls.csv';

if (file_exists($source_urls_csv)) {
  // Log all the errors together.
  $error_log = [];

  $file_lines = file($source_urls_csv);
  // Get rid of the CSV header.
  array_shift($file_lines);

  // Iterate through all the lines and extract the URL and title.
  foreach ($file_lines as $index => $file_line) {
    $line_tokens = array_map(
      function ($value) {
        return trim($value);
      },
      array_filter(
        explode("\t", $file_line),
        function ($value) {
          return !empty(trim($value));
        }
      )
    );

    $title = trim(array_shift($line_tokens));
    $url = trim(array_shift($line_tokens));

    $file_path = __DIR__ . '/../content/' . str_replace('http://', '', $url);

    if (!file_exists($file_path)) {
      fwrite(STDERR, "File not found: $file_path; Source URL unreachable?\n");
      continue;
    }
    $dom = new Dom;
    $dom->loadFromFile($file_path);

    $translations = dom_extract_translations($dom);
    $translations['DE'] = $url;
    fputcsv($fp, $translations);
    foreach ($translations as $lang => $tr) {
      if (trim($tr) != '') {
        file_put_contents($wget_urls, $tr . "\n", FILE_APPEND);
      }
    }
  }

  fclose($fp);
}


/**
 * Extract filtered body content from DOM as string.
 */
function dom_extract_translations($dom) {
  $links = $dom->find('#block-locale-0 li a');

  $translations = ['DE' => '', 'FR' => '', 'IT' => '', 'EN' => ''];
  foreach ($links as $link){
    $translations[$link->text] = $link->href;
  }
  return $translations;
}

/**
 * Filter children from given DOM node with given predicate.
 */
function dom_filter_children_flat($node, $predicate) {
  $children = [];

  foreach ($node->getChildren() as $child) {
    if ($predicate($child)) {
      $children[] = $child;
    }

    if (method_exists($child, 'getChildren')) {
      $children = array_merge($children, dom_filter_children_flat($child, $predicate));
    }
  }

  return $children;
}
