<?php
#ini_set('display_errors', 0);
#int error_reporting ([ int $レベル ] )
#error_reporting ( ~E_ALL );
#error_reporting ( ~E_ERROR );

$settings_yml_path = "/../settings-devconf.yml";

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を置いたパスを入れます

$Top_path = dirname(__FILE__) . "/..";
$Url_data = null;
$Url_data_array = null;

function get_url_data_array()
{
    global $settings_yml_path;

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

function get_url_data( $num ){
    global $Url_data_array;
    return $Url_data_array[$num];
}

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

function get_path_from_url_data( $num , $part){
    global $Url_data_array;

    switch($part){
    case 'data':
        $ret = $Url_data_array[$num]['path'];
        break;
    case 'conf':
        $ret = $Url_data_array[$num]['conf_path'];
        break;
    case 'output':
        $ret = $Url_data_array[$num]['output_path'];
        break;
    default:
        //exit(200);
        echo "get_path_from_url_data " . $part . "<br>";
    }

    return $ret;
}

function get_path_list_by_url( $num , $part){
    $top_path = get_path_from_url_data($num, $part);

    switch($part){
    case 'data':
#        $pattern = "*.md";
        $regexp = '".*\(md\|yml\)"';
#        $regexp = '".*\(yml\)"';
 #       $cmd_line_items = array("find" , $top_path , "-name", $pattern);
        $cmd_line_items = array("find" , $top_path , "-regex", $regexp);
        break;
    case 'conf':
        $regexp = '".*[^~]"';
        $cmd_line_items = array("find" , $top_path , "-type", "f", "-regex" , $regexp);
        break;
    case 'output':
        $regexp = '".*htm[^~]"';
        $cmd_line_items = array("find" , $top_path , "-type", "f", "-regex" , $regexp);
        break;
    default:
        echo "get_path_list_by_url=" . $part . "<br>";
        exit(100);
    }
    $cmd_line = implode(" " , $cmd_line_items);

    exec($cmd_line, $results, $ret_code);
    
    if( $ret_code === 0 ){
        $array = array();
        foreach($results as $buffer){
            $line = trim($buffer);
            $data = explode($top_path,  $line)[1];
            array_push($array , $data);
        }
        $array_x = array( "top_path" => $top_path, "file_list" => $array);
   }
    else{
        $array_x = array( );
    }
    return $array_x;
}

function restrict_filelist( $num, $path_info , $part ) {
    if( $part === "conf" ){
        $pathinfox = new ns\PathInfo($part, $path_info["top_path"]);
    }
    else{
        $output_htmls = get_restrict_basenames( $num );
        $pathinfox = new ns\PathInfo($part, $path_info["top_path"] , $output_htmls);

        foreach($path_info["file_list"] as $path){
            $pathinfox->scan($path);
        }
    }

    foreach($path_info["file_list"] as $path){
        $pathinfox->register($path);
    }

    return $pathinfox->pathinfo_list_in_json();
}

function get_path_info( $num , $part){
    $path_info = get_path_list_by_url( $num , $part);

    return restrict_filelist( $num, $path_info , $part);
 }

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

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

    return $path;
}

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

function build_one_html( $top_path, $num , $md_path , $part) {
    $pathinfo = pathinfo( $md_path );
    $md_fname = $pathinfo['basename'];
    
    $base = $pathinfo['filename'];

    $list = get_site_tsv( $num );

    $t = $list[$base]["t"];
    $s = $list[$base]["s"];
    $output_html = $list[$base]["output_html"];

    $url_data = get_url_data( $num );
    $bundle_path = $url_data["bundle_path"];
    $conf_path = $url_data["conf_path"];
    $output_url = $url_data["output_url"];

    $cmd_line_items = array( $top_path . "/bin/build.sh" , $bundle_path , $t, $s, $conf_path);

    $cmd_line = implode(" " , $cmd_line_items);

    
    exec($cmd_line, $results, $ret_code);
    if( $ret_code === 0 ){
        $full_download_url = implode( "/" , array( $output_url , $output_html ) );

        $html_fname_tmp = $output_html  . ".tmp";
        $partial_download_url = implode( "/" , array( $output_url , $html_fname_tmp) );

        $info = array( "full_download_url" => $full_download_url,
                   "partial_download_url" => $partial_download_url );
    }
    else{
        $info = array();
    }
    return $info;
}

function cmdx(){
    global $Top_path;
    global $Url_data;
    global $Url_data_array;

    $Url_data_array = get_url_data_array();

    $filelist_filename = array("data"=> "filelist.json", "conf"=> "conf-filelist.json", "output" => "output-filelist.json");
    $output_url_filename = "output_url.json";
    #    $storage_dir = dirname(__FILE__) . '/../storage';
    $storage_dir = dirname(__FILE__) . '/../storage-devconf';

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

            $Url_data = get_url_data($num);

            if (isset($_GET['part'])) {
                $part = $_GET['part'];

                switch ($cmd) {
                case 'get_content':
                    if (isset($_GET['path'])) {
                        $path = $_GET['path'];
                        $content = get_content( $num , $path , $part );
                    }
                    break;
                case 'update_filelistx':
                    $path = ensure_storage_dir( $storage_dir , $num, $filelist_filename[$part] );
                    $content = get_path_info( $num , $part);
                    output_file( $path , $content );
                    break;
                case 'get_filelistx':
                    $path = ensure_storage_dir( $storage_dir , $num, $filelist_filename[$part] );
                    if( file_exists($path) ){
                        $content = input_file( $path );
                    }
                    else {
                        $content = get_path_info( $num , $part);
                        output_file( $path , $content );
                    }
                    break;
                default:
                    break;
                }
            }
            else{
                switch ($cmd) {
                case 'get_output_url':
                    $info = array('output_url' => get_output_url($num));
                    $content = json_encode($info);
                    break;
                case 'update_output_url_listx':
                    $content = update_output_url_list( $num );
                case 'get_output_url_listx':
                    $path = ensure_storage_dir( $storage_dir , $num , $output_url_filename );
                    if( file_exists($path) ){
                        $content = input_file( $path );
                    }
                    else {
                        $content = update_output_url_list( $num );
                    }
                    break;
                default:
                    $content = "bad cmd=" . $cmd;
                    break;
                }
            }
        }
    }

    elseif (isset($_POST['cmd'])) {
        $cmd = $_POST['cmd'];
        if (isset($_POST['num'])) {
            $num = $_POST['num'];

            $Url_data = get_url_data($num);

            if (isset($_POST['part'])) {
                $part = $_POST['part'];

                switch ($cmd) {
                case 'build_one_html':
                    $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 , $part);
                        $filename_abs_path = $top_path . DIRECTORY_SEPARATOR . $path;
                        $ret = build_one_html( $Top_path , $num, $path, $part );
                    }
                    else{
#                        output_file( dirname(__FILE__) . "/debug-F.txt" , "ABCDEFG" );
                        $ret = "P-UPLOAD_CONTENT-NO-PATH";
                    }
                    $content = json_encode( $ret );
                    break;
                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 , $part);
                        $filename_abs_path = $top_path . DIRECTORY_SEPARATOR . $path;
                        
                        output_file( $filename_abs_path , $upload_content );
                        $content = $upload_content;
                    }
                    else{
                        $content = json_encode("P-UPLOAD_CONTENT-NO-PATH");
                    }
                    
                default:
#                    debug_x("P-DEFAULT");
                    /* $content = "P-DEFAULT";*/
                    break;
                }
            }
        }
        else{
            $content = json_encode("P-NO_NUM");
#            $content = json_encode("{pxyz:123}");
        }
    }
    else{
#        debug_x('DEFAULT');
    }

    if(!is_null($content)){
#        $content = "PABCEDFG";
        echo($content);
#        debug_x("CONTENT");
    }
    else{
        echo("no content");
    }
}

function debug_x($mes, $fname = null) {
    ob_start();
    echo $mes . "\n";
    /*    var_dump($_GET);*/
    /*    var_dump($_POST);*/
    ob_end_clean();
    $contentx = ob_get_contents();
    if( $fname === null ){
        $fname = './debug.txt';
    }

    error_log($contentx, 3, $fname );
}

function debug_vd($var) {
    ob_start();
    var_dump( $var );
    ob_end_clean();
    $content = ob_get_contents();
    output_file( "debug.txt" , $content );
}

function get_full_path($num, $key, $fname){
    global $Url_data_array;
    return $Url_data_array[$num][$key] . "/" . $fname;
}

function get_restrict_from_settings_yml( $num ) {
    global $Url_data_array;

    /*    $settings = get_url_data_array();*/
    $settings = $Url_data_array;
    if( !isset($settings[$num]) ){
        return array();
    }
    $array = $settings[$num]['restrict'];
    if( !isset( $array ) ){
        return array();
    }

    $r_keys = array_keys( $array );
    $restrict_array = array();
    foreach( $array as $k => $v ){
        $restrict_array[$k] = array();
        foreach( $v as $k2 => $v2 ){
            $restrict_array[$k][$k2] = array();
            foreach( $v2 as $k3 => $v3 ){
                foreach( $v3 as $k4 => $v4 ){
                    $restrict_array[$k][$k2][$v4] = "";
                }
            }
        }
    }

    return $restrict_array;
}

function get_restrict_basenames( $num ) {
    $output_htmls = array();

    $list = get_site_tsv($num );

    $restrict_array = get_restrict_from_settings_yml( $num );

    foreach( $list as $k => $v ){
        if( isset( $restrict_array[ $v['category'] ][ $v['t'] ][ $v['s'] ] ) ) {
            $output_htmls[$k] = $v['output_html'];
        }
    }

    return $output_htmls;
}

function get_site_tsv($num){
    $list = array();

    $fname = get_full_path( $num, 'conf_path' , 'site.tsv');
    if (($f = fopen( $fname , "r" )) !== FALSE) {
        while (($data = fgetcsv($f, 1000, "\t")) !== FALSE) {
            if( !preg_match("/^#/" , $data[0]) ){
                $t = $data[0];
                $s = $data[1];
                $category = $data[2];
                $output_html = $data[3];
                if( count($data) > 4 ){
                    $alias_html = $data[4];
                }
                else{
                    $alias_html = "";
                }
                $basename = basename( $output_html , ".html");
                $list[$basename] = array( 't'=> $t, 's'=> $s, 'category'=>$category, 'output_html' => $output_html, 'alias_html'=> $alias_html );
            }
        }
        fclose($f);
    }

    return $list;
}

function update_output_url_list( $num ){
    $json_data = get_output_url_list( $num );
    $content = json_encode($json_data);
    output_file( $path , $content );

    return $content;
}

function get_output_url_list( $num ){
    $output_url = get_output_url($num);
    $data = array( "output_url" => get_output_url($num),
           "htmlfname" => array()
    );

    $list = get_site_tsv( $num );
    $restrict_htmlnames = get_restrict_basenames( $num );

    $output_path = get_path_from_url_data( $num, 'output' );
    foreach( $list as $k => $v ){
        $htmlfname = $v["output_html"];
        if( $htmlfname !== null ){
            $array = array( "full" => "", "partial" => "" );
            if( !isset( $restrict_htmlnames[$htmlfname] ) ){
                $fpath =  $output_path . '/' . $htmlfname;
                if( file_exists($fpath) ){
                    $array["full"] = $htmlfname;
                }
                $fpath_tmp =  $fpath . '.tmp';
                if( file_exists($fpath_tmp) ){
                    $array["partial"] = $htmlfname_tmp;
                }
                array_push( $data["htmlfname"] , $array);
            }
        }
    }

    return $data;
}

function get_output_url($num){
    return $Url_data['output_url'];
}

function get_restrict($num){
    /*    $settings = get_url_data_array();*/
    global $Url_data_array;
    return $Url_data_array[$num]['restrict'];
}

cmdx();

#echo json_encode( get_output_url_list(0) );
# var_dump( get_output_url_list(0) );
#var_dump( get_output_url_list(0) );
#echo json_encode( get_output_url_list(0) );
?>
