<?php

namespace libphonenumber\buildtools;

use libphonenumber\PhoneNumberToTimeZonesMapper;

/**
 * Class GenerateTimeZonesMapData
 * @package libphonenumber\buildtools
 * @internal
 */
class GenerateTimeZonesMapData
{
    const GENERATION_COMMENT = <<<'EOT'
/**
 * This file has been @generated by a phing task by {@link GenerateTimeZonesMapData}.
 * See [README.md](README.md#generating-data) for more information.
 *
 * Pull requests changing data in these files will not be accepted. See the
 * [FAQ in the README](README.md#problems-with-invalid-numbers] on how to make
 * metadata changes.
 *
 * Do not modify this file directly!

 */


EOT;
    private $inputTextFile;

    public function __construct($inputFile, $outputDir)
    {
        $this->inputTextFile = $inputFile;

        if (!\is_readable($this->inputTextFile)) {
            throw new \RuntimeException('The provided input text file does not exist.');
        }

        $data = $this->parseTextFile();
        $this->writeMappingFile($outputDir, $data);
    }

    /**
     * Reads phone prefix data from the provided input stream and returns a SortedMap with the
     * prefix to time zones mappings.
     */
    private function parseTextFile()
    {
        $data = \file($this->inputTextFile);

        $timeZoneMap = array();

        foreach ($data as $line) {
            // Remove \n
            $line = \str_replace(array("\n", "\r"), '', $line);
            $line = \trim($line);

            if (\strlen($line) == 0 || \substr($line, 0, 1) == '#') {
                continue;
            }
            if (\strpos($line, '|')) {
                // Valid line
                $parts = \explode('|', $line);


                $prefix = $parts[0];
                $timezone = $parts[1];

                $timeZoneMap[$prefix] = $timezone;
            }
        }

        return $timeZoneMap;
    }

    private function writeMappingFile($outputFile, $data)
    {
        $phpSource = '<?php' . PHP_EOL
            . self::GENERATION_COMMENT
            . 'return ' . \var_export($data, true) . ';'
            . PHP_EOL;

        $outputPath = $outputFile . DIRECTORY_SEPARATOR . PhoneNumberToTimeZonesMapper::MAPPING_DATA_FILE_NAME;

        \file_put_contents($outputPath, $phpSource);
    }
}
