<?php

$url = 'http://c...content-available-to-author-only...l.cx/api/';
$commands = array(
	'enter' => 1,
	'read' => 1,
	'write' => 1,
	'leave' => 1
);

function postit($cmd, $msg = '') {
	global $url, $name, $commands;
	if (!isset($commands[$cmd])) {
		return false;
	}
	$data = array('name' => $name);
	if ($cmd == 'write') {
		if (!isset($msg)) {
			return false;
		}
		$data['body'] = mb_convert_encoding($msg, "UTF-8", "SJIS");
	}
    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url . $cmd);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

    $result = curl_exec($curl);

    curl_close($curl);
    
    return $result;
}

do {
    echo 'Name?: ';
    $name = rtrim(fgets(STDIN));
} while ($name == false);
$name = mb_convert_encoding($name, "UTF-8", "SJIS");

if (postit('enter') === false) {
    die("failed to enter." . PHP_EOL);
}

do {
    if (($json = postit('read')) === false) {
        die("failed to read." . PHP_EOL);
    }
    $chat = json_decode($json);
    foreach ($chat as $value) {
        echo '[', $value->time, ']', mb_convert_encoding($value->name, "SJIS", "UTF-8")
                ,': ', mb_convert_encoding($value->body, "SJIS", "UTF-8"), PHP_EOL;
    }
    echo PHP_EOL;
    
    echo 'Command: write read leave', PHP_EOL;
    do {
        echo '? ';
        $cmd = rtrim(fgets(STDIN));
    } while (!isset($commands[$cmd]));
    
    if ($cmd == 'write') {
        do {
            echo 'message? ';
            $mes = rtrim(fgets(STDIN));
        } while ($mes == false);
        if (postit('write', $mes) === false) {
            die('failed to write.' . PHP_EOL);
        }
    }
} while ($cmd != 'leave');

postit('leave');

?>