#!/usr/bin/env php
<?php
/**
 * kcbasic初始化工具
 */
echo "KcDev Initialization Tool v1.0\n\n";

/* 检查openssl模块是否已经安装并正确加载 */
if (!extension_loaded('openssl')) {
    die('The OpenSSL PHP extension is required by Yii2.');
}

$root = str_replace('\\', '/', __DIR__);

/* 输入app名称 */
echo "Please enter the app name:";
$appName = trim(strtolower(fgets(STDIN)));

if (!preg_match('/^[_a-z]{3,12}$/i', $appName)) {
    printError("App name must be 3 to 12 letters or underline");
    exit();
}


if (is_dir($root . '/' . $appName)) {
    printError("App {$appName} is exists");
    exit();
}

/* 输入app类型 */
$types = ["web application", "wechat application", "restfull api"];
echo "\n\nPlease select the type of your app.\n";
foreach ($type as $i => $name) {
    echo "  [$i] $name\n";
}
echo "\n  Your choice [0-" . (count($types) - 1) . ', or "q" to quit] ';
$answer = trim(fgets(STDIN));

if (!ctype_digit($answer) || !in_array($answer, range(0, count($types) - 1))) {
    printError("Please enter the correct nunmber");
    exit();
}
$type = $answer;

//TODO 后面希望通过这个脚本 可以创建web后台 H5前台 API等程序的基础模板,这些模板保存在environment目录里面



/**
 * Prints error message.
 * @param string $message message
 */
function printError($message) {
    echo "\n  " . formatMessage("Error. $message", ['fg-red']) . " \n";
}

/**
 * Returns true if the stream supports colorization. ANSI colors are disabled if not supported by the stream.
 *
 * - windows without ansicon
 * - not tty consoles
 *
 * @return boolean true if the stream supports ANSI colors, otherwise false.
 */
function ansiColorsSupported() {
    return DIRECTORY_SEPARATOR === '\\' ? getenv('ANSICON') !== false || getenv('ConEmuANSI') === 'ON' : function_exists('posix_isatty') && @posix_isatty(STDOUT);
}

/**
 * Get ANSI code of style.
 * @param string $name style name
 * @return integer ANSI code of style.
 */
function getStyleCode($name) {
    $styles = [
        'bold' => 1,
        'fg-black' => 30,
        'fg-red' => 31,
        'fg-green' => 32,
        'fg-yellow' => 33,
        'fg-blue' => 34,
        'fg-magenta' => 35,
        'fg-cyan' => 36,
        'fg-white' => 37,
        'bg-black' => 40,
        'bg-red' => 41,
        'bg-green' => 42,
        'bg-yellow' => 43,
        'bg-blue' => 44,
        'bg-magenta' => 45,
        'bg-cyan' => 46,
        'bg-white' => 47,
    ];
    return $styles[$name];
}

/**
 * Formats message using styles if STDOUT supports it.
 * @param string $message message
 * @param string[] $styles styles
 * @return string formatted message.
 */
function formatMessage($message, $styles) {
    if (empty($styles) || !ansiColorsSupported()) {
        return $message;
    }

    return sprintf("\x1b[%sm", implode(';', array_map('getStyleCode', $styles))) . $message . "\x1b[0m";
}
?>