<?php

namespace Giggsey\Locale\Build;

use InvalidArgumentException;
use RuntimeException;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\OutputInterface;

class DataBuilder
{
    const GENERATION_HEADER = <<<EOT
/**
 * This file has been @generated by a phing task from CLDR version {{ version }}.
 * See [README.md](README.md#generating-data) for more information.
 *
 * @internal Please do not require this file directly.
 * It may change location/format between versions
 *
 * Do not modify this file directly!
 */


EOT;

    /**
     * Ignore these locales
     * @var array
     */
    private $ignoredLocales = array(
        'en-US-POSIX',
        'en-001',
        'en-150',
        'es-419',
    );

    /**
     * Ignore these regions
     * @var array
     */
    private $ignoredRegions = array(
        'ZZ', // Unknown region
        'QO', // Outlying Ocean Region
        'EU', // European Union
        'AN', // Antilles (no longer exists)
        'BV', // Bouvet Island (Uninhabited)
        'HM', // Heard & McDonald Islands (Uninhabited)
        'CP', // Clipperton Island (uninhabited)
        'EZ', // Eurozone
        'UN', // United Nations
        'XA', // Pseudo-Accents
        'XB', // Pseudo-Bidi
    );

    /**
     * @param string $version Version of the CLDR data
     * @param string $inputDir Input directory to load CLDR data from
     * @param string $outputDir Output directory to write data
     * @param OutputInterface $output
     */
    public function generate($version, $inputDir, $outputDir, OutputInterface $output)
    {
        // Check Directories exist
        $this->checkDirectories($inputDir, $outputDir);

        // Load Locales from source directory
        $localeList = $this->loadLocales($inputDir);

        // Load list of Territories
        $countries = $this->loadTerritories($inputDir, $localeList);

        $progress = new ProgressBar($output, count($countries));

        // Write each file
        $writtenCountries = array();

        foreach ($countries as $locale => $countryData) {
            /*
             * Compress file (if possible)
             *
             *  - Split up the locale into the sections
             *  - Loop through each row in $countryData
             *  - If the record exists, and is the same as a higher level, remove from this level
             */

            $fallbackParts = explode('-', str_replace('_', '-', $locale));
            if (count($fallbackParts) > 1) {
                array_pop($fallbackParts);

                $newLocale = implode('-', $fallbackParts);

                if (array_key_exists($newLocale, $countries)) {
                    foreach ($countryData as $key => $value) {
                        if (array_key_exists($key, $countries[$newLocale]) && $countries[$newLocale][$key] === $value) {
                            unset($countryData[$key]);
                        }
                    }
                }
            }

            if (count($countryData) == 0) {
                // Skip empty countries
                continue;
            }

            $this->writeTerritoryFile($outputDir, $version, $locale, $countryData);

            $writtenCountries[strtolower($locale)] = '';

            $progress->advance();
        }

        $this->writeMappingFile($outputDir, $version, $writtenCountries);

        $this->writeVersionFile($outputDir, $version);

        $progress->finish();
    }

    /**
     * Check and create directories
     *
     * @param string $inputDir
     * @param string $outputDir
     * @codeCoverageIgnore Ignore for unit test coverage
     */
    private function checkDirectories($inputDir, $outputDir)
    {
        if (!is_dir($inputDir)) {
            throw new InvalidArgumentException(sprintf("Unable to find input directory: %s", $inputDir));
        }

        if (!is_dir($outputDir)) {
            // Try to create output directory
            if (mkdir($outputDir) === false) {
                throw new RuntimeException(sprintf("Unable to create output directory: %s", $outputDir));
            }
        }
    }

    /**
     * Load Locale list from the source data
     *
     * @param string $inputDir Input Directory
     * @return array List of Locales
     */
    private function loadLocales($inputDir)
    {
        $localeList = array();

        foreach (scandir($inputDir) as $item) {
            if (substr($item, 0, 1) !== '.' && is_dir($inputDir . $item)) {
                if (in_array($item, $this->ignoredLocales)) {
                    // Skip over any ignored locales
                    continue;
                }

                $localeList[] = $item;
            }
        }

        return $localeList;
    }

    /**
     *
     *
     * @param string $inputDir
     * @param array $localeList
     * @return array
     */
    protected function loadTerritories($inputDir, $localeList)
    {
        $countries = array();

        foreach ($localeList as $locale) {
            $data = json_decode(file_get_contents($inputDir . $locale . '/territories.json'), true);
            $territoryList = $data['main'][$locale]['localeDisplayNames']['territories'];

            $countries[$locale] = array();

            foreach ($territoryList as $territory => $name) {
                if (is_numeric($territory)) {
                    // Ignore numeric values (continents, and other special regions)
                    continue;
                }

                if (stripos($territory, '-alt-') !== false) {
                    // Ignore alternative names
                    continue;
                }

                if (in_array($territory, $this->ignoredRegions)) {
                    // Ignore certain regions
                    continue;
                }

                if ($territory === $name) {
                    // Ignore the data if it's the same as the territory name
                    continue;
                }

                $countries[$locale][$territory] = $name;
            }
        }

        return $countries;
    }

    /**
     * @param string $outputDir
     * @param string $version CLDR Version
     * @param string $locale
     * @param array $data
     * @return string
     */
    private function writeTerritoryFile($outputDir, $version, $locale, $data)
    {
        $phpSource = '<?php'
            . PHP_EOL
            . $this->generateFileHeader($version)
            . 'return ' . var_export($data, true) . ';'
            . PHP_EOL;

        file_put_contents($outputDir . strtolower($locale) . '.php', $phpSource);
    }

    private function writeMappingFile($outputDir, $version, $countryList)
    {
        $phpSource = '<?php'
            . PHP_EOL
            . $this->generateFileHeader($version)
            . 'return ' . var_export($countryList, true) . ';'
            . PHP_EOL;

        file_put_contents($outputDir . '_list.php', $phpSource);
    }

    private function writeVersionFile($outputDir, $version)
    {
        $phpSource = '<?php'
            . PHP_EOL
            . $this->generateFileHeader($version)
            . 'return ' . var_export($version, true) . ';'
            . PHP_EOL;

        file_put_contents($outputDir . '_version.php', $phpSource);
    }

    private function generateFileHeader($version)
    {
        return str_replace('{{ version }}', $version, static::GENERATION_HEADER);
    }
}
