<?php

/**
 * This program is copyrighted by Franz Geffke (Softmax Co., Ltd.)
 */

namespace ones\oidc;

use Symfony\Component\Yaml\Yaml;
use Exception;

/**
 * Read device config from YAML file
 * 
 * @param string $filename
 * @return array{
 *     client_id: string,
 *     config_version: string,
 *     domain: string,
 *     host: string,
 *     id: string,
 *     initiated_on: string,
 *     is_managed: bool,
 *     key_security: string,
 *     key_type: string,
 *     location: string,
 *     role: string,
 *     title: string
 * }
 */
function read_device_config($filename) {
    $content = Yaml::parseFile($filename);

    return [
        'client_id' => $content['client_id'],
        'config_version' => $content['config_version'],
        'domain' => $content['domain'],
        'host' => $content['host'],
        'id' => $content['id'],
        'initiated_on' => $content['initiated_on'],
        'is_managed' => $content['is_managed'],
        'key_security' => $content['key_security'],
        'key_type' => $content['key_type'],
        'location' => $content['location'],
        'role' => $content['role'],
        'title' => $content['title']
    ];
}

/**
 * Read private key from file
 * 
 * @param string $filename
 * @return string
 */
function read_private_key($filename) {
    return file_get_contents($filename);
}

function get_device_properties(
    $deviceConfigPath,
    $devicePrivateKeyPath,
) {
    // Read device config
    $deviceConfig = null;
    try {
        $deviceConfig = read_device_config($deviceConfigPath);
    } catch (Exception $e) {
        throw new Exception("Error reading device config: " . $e->getMessage());
    }
    $clientId = $deviceConfig['client_id'];
    $host = $deviceConfig['host'];

    // Read private key
    $privateKey = null;
    try {
        $privateKey = read_private_key($devicePrivateKeyPath);
    } catch (Exception $e) {
        throw new Exception("Error reading private key: " . $e->getMessage());
    }

    return [
        'clientId' => $clientId,
        'host' => $host,
        'privateKey' => $privateKey
    ];
}

?>