#!/usr/bin/php
<?php

require_once(__DIR__."/lib/Arr.php");
require_once(__DIR__."/lib/goCLI/class.gocli.php");

use Sku\Lib\Arr;

$param = parse_arguments();
$data = load_data_from($param['file']);

if(isset($param['key']) && isset($param['value'])) {
    $old = Arr::get($data, $param['key']);
    Arr::set($data, $param['key'], $param['value']);
    file_put_contents($param['file'], json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    echo $param['key'].' changed from "'.$old.'" to "'.$param['value'].'" in '.$param['file']."\n";
} elseif(isset($param['key']) && isset($param['delete'])) {
    $old = Arr::get($data, $param['key']);
    Arr::forget($data, $param['key']);
    file_put_contents($param['file'], json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    echo $param['key']." deleted from ".$param['file']." (was \"$old\")\n";
} elseif(isset($param['key'])) {
    $notfoundflag = md5(rand().date("YmdHis"));
    $key = Arr::get($data, $param['key'], $notfoundflag);
    if($key == $notfoundflag) {
        exit(1);
    }
    echo is_string($key)?
        $key :
        json_encode($key, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ;
} else {
    try {
        echo file_get_contents($param['file']);
    } catch (\Exception $e) {
        echo "Couldn't read file: ".$param['file'];
        exit(2);
    }
}

function load_data_from($file) {
    $data = [];
    if( file_exists($file) ) {
        $raw_data = file_get_contents($file);
        $data = json_decode($raw_data, JSON_OBJECT_AS_ARRAY);
    }
    return $data;
}





function parse_arguments() {


    $expected_params = array(

        'help' =>
            array(
                'short'		=> 'h',
                'long'		=> 'help',
                'info'		=> 'Show this help page.',
                'switch'	=> TRUE,
                'help'		=> TRUE
            ),

        'key' =>
            array(
                'short'		=> 'k',
                'long'		=> 'key',
                'info'		=> 'The key to read or modify. Example: -k="db.user"'
            ),

        'value' =>
            array(
                'short'		=> 'v',
                'long'		=> 'value',
                'info'		=> 'The value to assign to the specified key. Example: -k="db.user" -v="root"'
            ),

        'delete' =>
            array(
                'short'		=> 'd',
                'long'		=> 'delete',
                'info'		=> 'Flag that indicates that the referred key must be deleted. Example: -k="db.user" -d'
            ),

        'file' =>
            array(
                'short'		=> '',
                'long'		=> '',
                'info'		=> 'JSON file to read or modify.',
                'argument'  => 'file',
                'required'	=> TRUE
            )

    );


    $cCLI = new Sku\Lib\Gocli\goCLI($expected_params);
    $param = $cCLI->go();

    return $param;
}
