<?php
namespace EasyChat\Library;

class EasyTokensClientHeaders {
    public static function append(array $headers): array {
        $existing = [];
        foreach ($headers as $header) {
            $name = self::headerName($header);
            if ($name !== '') {
                $existing[$name] = true;
            }
        }

        foreach (self::headers() as $header) {
            $name = self::headerName($header);
            if ($name !== '' && !isset($existing[$name])) {
                $headers[] = $header;
                $existing[$name] = true;
            }
        }

        return $headers;
    }

    public static function headers(): array {
        $version = self::version();
        return [
            'X-EasyChat-Client: EasyChat/' . $version,
            'X-EasyChat-Version: ' . $version,
        ];
    }

    public static function version(): string {
        if (!defined('EASYCHAT_VERSION')) {
            $versionFile = dirname(__DIR__) . '/version.php';
            if (is_file($versionFile)) {
                require_once $versionFile;
            }
        }

        $version = defined('EASYCHAT_VERSION') ? (string)EASYCHAT_VERSION : '';
        return preg_match('/^[0-9]+\\.[0-9]+\\.[0-9]+(?:[-+][A-Za-z0-9._-]+)?$/', $version)
            ? $version
            : '1.0.0';
    }

    private static function headerName($header): string {
        $header = (string)$header;
        $pos = strpos($header, ':');
        if ($pos === false) {
            return '';
        }
        return strtolower(trim(substr($header, 0, $pos)));
    }
}
