<?php

namespace pictpostpersonal\controller\api;

use pictpostpersonal\controller\ControllerBase;
use pictpostpersonal\Result;
use pictpostpersonal\Request;
use pictpostpersonal\Utility;

/**
 * 
 * ページ移動記録APIを提供するクラス
 * 
 */
class NavigateApi extends ControllerBase
{

    /**
     * セッションに移動記録を追記する
     *
     * @param Request $req
     * 
     * @return result
     * 
     */
    function write(Request $req): result
    {
        Utility::SessionStart();

        $url = $req->getArgs('url', '');
        $history = json_decode($_SESSION['move_history'] ?? '');

        if (!$url) {
            //空の場合何もしない
            return new Result(200, "{\"status\":\"success\"}");
        }

        $hit = array_search($url, $history);
        if ($hit) {
            $history = array_slice($history, 0, $hit + 1);
        }

        $history[] = $req->getArgs('url', '');
        $_SESSION['move_history'] = json_encode($history);
        return new Result(200, "{\"status\":\"success\"}");
    }


    /**
     * セッションから移動履歴を1件取り出す
     *
     * @param Request $req
     * 
     * @return result
     * 
     */
    function get(Request $req): result
    {
        Utility::SessionStart();
        $history = json_decode($_SESSION['move_history'] ?? '');
        $hit = array_search($req->getArgs('ref', ''), $history);
        if ($hit) {
            $history = array_slice($history, 0, $hit);
        }
        $url = array_pop($history);
        $_SESSION['move_history'] = json_encode($history);
        return new Result(200, "{\"status\":\"success\", \"url\":\"$url\"}");
    }

    /**
     * 移動記録をクリアする
     *
     * @param Request $req
     * 
     * @return result
     * 
     */
    function delete_all(Request $req): result
    {
        Utility::SessionStart();
        $_SESSION['move_history'] = '[]';
        return new Result(200, "{\"status\":\"success\"}");
    }
}
