#!/usr/bin/php -q
<?php

if (count($argv) < 2){
    echo 'wrong amount of parameters for this command';?>

    <?php
    echo "usage example: ./gvconsole create-controller {Controllername}Users {methods...}list create update delete";
    exit(0);
}

const CONTROLLERS_PATH = __DIR__ . '/../src/Controllers/';

$name = ucfirst($argv[1]);
createFile($name, array_slice($argv, 2));

function createFile($fileName, $methods) {
    $classPath = CONTROLLERS_PATH . $fileName . ".php";
    if (file_exists($classPath)){
       exit("The controller already exists in the destination.");
    }
    $handle = fopen($classPath, 'a') or die('Cannot create file:  ' . $fileName);
    fwrite($handle, openClass($fileName));
    fclose($handle);
    createMethods($methods, $classPath);
    chmod($classPath, 0777);
}


function openClass($className) {
    return "<?php
namespace Gvera\Controllers;

class ". $className ." extends GvController
{
";
}

function closeClass() {
    return "\n
}
";
}

function createMethods($methods, $classPath) {
    foreach ($methods as $method) {
        $handle = fopen($classPath, 'a') or die('Cannot create file:  '.$classPath);
        fwrite($handle, appendMethod($method));
        fclose($handle);
    }

    $handle = fopen($classPath, 'a') or die('Cannot create file:  '.$classPath);
    fwrite($handle, closeClass());
    fclose($handle);
}

function appendMethod($methodName) {
    return
        "    public function ".$methodName."() 
    {
        //TODO: Implement this
    }";
}
