<?php
//=====================================
// Questioner.php (stub version)
//
// Created by M.Miyazaki on 2015.05.24
//
// version 1.0 created by y.a on 08.09
//=====================================

/***** Configurations *****/

/**
 * HTTP_METHOD
 *
 * Type of HTTP method.
 * Specify "GET" or "POST" as string.
 */
define("HTTP_METHOD", "GET");

/***** Main routine *****/

include 'QuestionDB.php';
include 'Question.php';
perform();
exit(0);   // Success execution

/***** Sub routines *****/

/**
 * perform
 *
 * This function is just like 'main' with C-lang.
 * Describe all works here.
 */
function perform()
{
    $request   = getRequest();
    $arguments = getArguments();

    if ($arguments)
    {
        $arguments = json_decode($arguments);
    }

    switch ($request)
    {
        case "getNumberOfQuestions":
            doGetNumberOfQuestions();
            break;
        case "getQuestion":
            doGetQuestion();
            break;
        case "getQuestionById":
            doGetQuestionById($arguments);
            break;
        case "getQuestions":
            doGetQuestions($arguments);
            break;
        case "setQuestion":
            doSetQuestion($arguments);
            break;
        // 20150813 AddCases by Y.A.
        // start
        case "getAllQuestions":
            doGetAllQuestions($arguments);            
            break;
        case "deleteQuestion":
            doDeleteQuestion($arguments);
            break;
        // end
        default:
            break;
    }

    return;
}

/**
 * getRequest
 * 
 * Return the type of request.
 * ex) "getQuestion", "getNumberOfQuestions", etc...
 */
function getRequest()
{
    return getAttributeInHttpRequest("request");
}

/**
 * getArguments
 * 
 * Return the arguments in JSON array format.
 * ex) '["3","hoge",["foo","bar"]]', '["124"]', etc...
 */
function getArguments()
{
    return getAttributeInHttpRequest("arguments");
}

/**
 * getAttributeInHttpRequest
 *
 * Return a value of attribute you specify.
 * If it is NOT defined, return null.
 *
 * @param attributeName  Name of attribute.
 * @return Value of attribute you specify.
 */
function getAttributeInHttpRequest($attributeName)
{
    if (!$attributeName) return null;

    $value = null;

    if (HTTP_METHOD == "POST" && array_key_exists($attributeName, $_POST))
    {
        $value = $_POST[$attributeName];
    }
    else if (HTTP_METHOD == "GET" && array_key_exists($attributeName, $_GET))
    {
        $value = $_GET[$attributeName];
    }

    return $value;
}

/**
 * createResponse
 *
 * Create the response string in JSON format.
 *
 * @param request  Name of request.
 * @param data  Response data in JSON format.
 * @return Response string.
 */
function createResponse($request, $data)
{
    return sprintf('{"%s":%s}', $request, $data);
}

/**
 * doGetNumberOfQuestions
 *
 * 問題総数を取得し応答します。
 */
function doGetNumberOfQuestions()
{
    $request     = "getNumberOfQuestions";

    $aQuestionDB = new QuestionDB();
    $aNumber     = $aQuestionDB -> getNumberOfQuestion();
    $data        = '"' . (string)$aNumber . '"';
    $output      = createResponse($request, $data);

    print($output);

    return;
}

/**
 * doGetQuestion
 *
 * 問題を１つランダムに取り出し応答します。
 */
function doGetQuestion()
{
    $request     = "getQuestion";

    $aQuestionDB = new QuestionDB();
    $aQuestion   = $aQuestionDB -> getQuestion();
    $anIdInteger = $aQuestion -> getId();
    $data        = '["' . (string)$anIdInteger . '", "' . $aQuestion -> getQuestion() . '", ' . $aQuestion -> getCorrectAnswersInJSON() . ', ' . $aQuestion -> getIncorrectAnswersInJSON() . ']';
    $output      = createResponse($request, $data);

    print($output);

    return;
}

/**
 * doGetQuestionById
 *
 * 指定されたIDの問題を取り出し応答します。
 */
function doGetQuestionById($arguments)
{
    $id      = $arguments[0];
    $request = "getQuestionById";
 
    $aQuestionDB = new QuestionDB();
    $aQuestion   = $aQuestionDB -> getQuestionById((integer)$id);

    $data    = '["' . $id . '", "' . $aQuestion -> getQuestion() . '", '. $aQuestion -> getCorrectAnswersInJSON() .', ' . $aQuestion -> getIncorrectAnswersInJSON() . ']';
    $output  = createResponse($request, $data);

    print($output);

    return;
}

/**
 * doGetQuestions
 *
 * 引数に指定された数分だけ問題を取り出し応答します。
 * 取り出し方はランダムです。
 */
function doGetQuestions($arguments)
{
    $number    = $arguments[0];
    $request   = "getQuestions";
    $dataArray = array();

    $aQuestionDB = new QuestionDB();
    $questions   = $aQuestionDB -> getQuestions((integer)$number);

    for ($index = 0; $index < (integer)$number; $index++)
    {
        $aQuestion   = $questions[$index];
        $anIdInteger = $aQuestion -> getId();
 
        $data = '["' . (string)$anIdInteger . '", "' . $aQuestion -> getQuestion() . '", '. $aQuestion -> getCorrectAnswersInJSON() .', ' . $aQuestion -> getIncorrectAnswersInJSON() . ']';

        array_push($dataArray, $data);
    }

    $data    = "[" . implode(",", $dataArray) . "]";
    $output  = createResponse($request, $data);

    print($output);

    return;
}

/**
 * doSetQuestion
 *
 * 引数に指定されている問題を登録します。
 * リクエスト形式例は以下の通りです。
 *
 * http://www.fukurous.org/path/to/Questioner.php?
 * request=setQuestion\&arguments=["", "ここは質問文です", ["正答1"], ["誤答1", "誤答2", "誤答3"]]
 *
 */
function doSetQuestion($arguments)
{
    $request = "setQuestion";

    $anIdString            = $arguments[0];
    $aQuestionString       = $arguments[1];
    $correctAnswersArray   = $arguments[2];
    $incorrectAnswersArray = $arguments[3];
  
    $aQuestion = new Question((integer)$anIdString,$aQuestionString,$correctAnswersArray,$incorrectAnswersArray);

    $aQuestionDB = new QuestionDB();
    $anIdNumber  = $aQuestionDB -> setQuestion($aQuestion);

    // IDは応答値として使わなくないためコメントアウト
    // print($anIdNumber);

    return;
}

/**
 * doGetAllQuestions
 *
 * すべての問題を取り出しQuestion型の配列で応答します。
 */
function doGetAllQuestions($arguments) {

    $request   = "getAllQuestions";
    $dataArray = array();

    $aQuestionDB = new QuestionDB();
    $allQuestionsArray = $aQuestionDB -> getAllQuestions();
    $allQuestionsArraySize = count($allQuestionsArray);

    for ($index = 0; $index < $allQuestionsArraySize; $index++)
    {
        $aQuestion   = $allQuestionsArray[$index];
        $anIdInteger = $aQuestion -> getId();

        $data = '["' . (string)$anIdInteger . '", "' . $aQuestion -> getQuestion() . '", '. $aQuestion -> getCorrectAnswersInJSON() .', ' . $aQuestion -> getIncorrectAnswersInJSON() . ']';

        array_push($dataArray, $data);
    }

    $data    = "[" . implode(",", $dataArray) . "]";
    $output  = createResponse($request, $data);

    print($output);

    return;
}

/**
 * doDeleteQuestion
 *
 * 識別子(id)を指定して問題を削除します。
 */
function doDeleteQuestion($arguments) {

    $request    = "deleteQuestion";
    $anIdString = $arguments[0];

    $aQuestionDB = new QuestionDB();
    $aQuestionDB -> deleteQuestion($anIdString);

    return;
}

?>