<?php

header("Access-Control-Allow-Origin: *");
#namespace ns;

require_once( dirname(__FILE__) . '/func.php');

require_once( dirname(__FILE__) . '/NorthernCross/ns/PathItem.php');
require_once( dirname(__FILE__) . '/NorthernCross/ns/PathInfo.php');
require_once( dirname(__FILE__) . "/spyc-0.5/spyc.php"); // ★の部分にはspyc.phpを置いたパスを入れます

function get_url_data_array()
{
        $yaml= spyc_load_file( dirname(__FILE__) . "/../settings.yml");// ☆の部分にはyamlファイルがあるパスを入れます
        return $yaml;
}

function get_url_data_array0()
{
	$array = array(
        array('url' => 'https://toppers.jp', 'path' =>	'/var/www/vhosts/devconf.northern-cross.info/httpdocs/a/tmp/devconf-guest-4/tmp/md2site-x/_xtest/wtjx/t12/src') );

	return $array;
}

function get_url_data( $num ){
    $array = get_url_data_array();
    return $array[$num];
}

function dump_url_data( $num ){
    print_r( get_url_data( $num ));	 
}

function get_path_from_url_data( $num ){
    return get_url_data( $num )['path'];
}

function get_path_list_by_url( $num ){
    $pattern = "*.md";
    $top_path = get_path_from_url_data($num);
    $cmd_line_items = array("find" , $top_path , "-name", $pattern);
    $cmd_line = implode(" " , $cmd_line_items);

    $array = array();
    $handle = popen( $cmd_line , "r");
    while (( $buffer = fgets($handle, 4096)) !== false){
        $line = trim($buffer);
        $data = explode($top_path,  $line)[1];
        array_push($array , $data);
    }
    if (!feof($handle)) {
	    echo "Error: unexpected fgets() fail\n";
    }
    pclose($handle);
    
    return array( "top_path" => $top_path, "file_list" => $array);
}


function dump_hier_list($pathinfo){
    foreach( array_keys($pathinfo->hier_hash) as $v ){
        $v2 = trim($v);
        if(is_null($v2)){
            echo "found null\n";
            exit(0);
        }
        echo $v . "||(" . strlen($v) . ")\n";
   }
}

function dump_hier($pathinfo) {
    foreach( array_keys($pathinfo->hier_hash) as $v ){
        echo $v . "\n";
        $item = $pathinfo->hier_hash[$v];
        $item->dump();
        echo "--dump_children\n";
        $item->dump_children();
        echo "#==========\n";
    }
}

function get_path_info( $num ){
    $path_info = get_path_list_by_url( $num );
    $pathinfo = new ns\PathInfo($path_info["top_path"]);
#    $pathinfo = new PathInfo($path_info["top_path"]);
    foreach($path_info["file_list"] as $path){
        $pathinfo->register($path);
    }
    return $pathinfo->pathinfo_list_in_json();
#    $pathinfo->dump();
#    $pathinfo->dump_root();
#    dump_hier_list($pathinfo);
}

function print_get_path_info( $num ){
    echo get_path_info( $num );
}

function ensure_dir( $dir ) {
    if( !file_exists( $dir ) ){
        mkdir( $dir );
    }
}

function ensure_storage_dir( $storage_dir , $num, $filename ) {
    $dir = implode( "/" , array( $storage_dir , $num) );
    mkdir($dir);
    $path = implode( "/" , array( $dir , $filename) );
    ensure_dir( $dir );

    return $path;
}

function get_content( $num , $path ) {
    $top_dir = get_path_from_url_data( $num );
    $full_path = implode( '/', [$top_dir, $path]);
    $result = input_file( $full_path );
    return $result;
}

function cmdx(){
    $filelist_filename = "filelist.json";
    $setting_filelist_filename = "setting-filelist.json";
    $storage_dir = dirname(__FILE__) . '/../storage';

    $content = NULL;
    if (isset($_GET['cmd'])) {
        $cmd = $_GET['cmd'];
        if (isset($_GET['num'])) {
            $num = $_GET['num'];

            switch ($cmd) {
            case 'get_setting_filelist':
                $path = ensure_storage_dir( $storage_dir , $num, $setting_filelist_filename );
                if( file_exists($path) ){
                    $content = input_file( $path );
                }
                else {
                    $content = get_path_info( $num );
                    output_file( $path , $content );
                }
                break;
            case 'build':
                break;
            case 'get_content':
                if (isset($_GET['path'])) {
                    $path = $_GET['path'];
                    $content = get_content( $num , $path );
                }
                break;
            case 'update_filelist':
                $path = ensure_storage_dir( $storage_dir , $num, $filelist_filename );
                $content = get_path_info( $num );
                output_file( $path , $content );
                break;
            case 'get_filelist':
                $path = ensure_storage_dir( $storage_dir , $num, $filelist_filename );
                if( file_exists($path) ){
                    $content = input_file( $path );
                }
                else {
                    $content = get_path_info( $num );
                    output_file( $path , $content );
                }
                break;
            default:
                break;
            }
        }
    }
    elseif (isset($_POST['cmd'])) {
        $cmd = $_POST['cmd'];
        if (isset($_POST['num'])) {
            $num = $_POST['num'];

            switch ($cmd) {
            case 'upload_content':
                $array = get_lines_from_formdata( "mytext" );
                $upload_content = implode( "\n" , $array );
                if (isset($_POST['path'])) {
                    $path = $_POST['path'];
                    $top_path = get_path_from_url_data( $num );
                    $filename_abs_path = $top_path . DIRECTORY_SEPARATOR . $path;

                    output_file( $filename_abs_path , $upload_content );
                    $content = "P-UPLOAD_CONTENT-OK=" . $filename_abs_path;
                }
                else{
                    $content = "P-UPLOAD_CONTENT-NO-PATH";
                }

            default:
                debug_x("P-DEFAULT");
                /* $content = "P-DEFAULT";*/
                break;
            }
        }
        else{
            $content = "P-NO_NUM";
        }
    }
    else{
        debug_x('DEFAULT');
    }

    if(!is_null($content)){
        echo( $content );
    }
}

function debug_x($mes) {
    ob_start();
    echo $mes . "\n";
    var_dump($_GET);
    var_dump($_POST);
    ob_end_clean();
    $content = ob_get_contents();
    error_log($content,3, './debug.txt');
}
#print_get_path_info( 0 );
#print_get_path_info( 1 );
cmdx();

?>
