<?php

use xmvc\Encoder;

function getFuncItemKey($parseArr, $function)
{
    $methods = $parseArr['methods'] ?: $parseArr['functions'];
    $result = false;
    foreach ($methods as $i => $item) {
        if ($item['name'] == $function) {
            $result = $i;
            break;
        }
    }
    return $result;
}
function save($parseFile, $function, $that)
{
    $summary = I('summary');
    $summaryArr = explode("\n", $summary);
    $parseArr = require($parseFile);
    $itemKey = getFuncItemKey($parseArr, $function);
    if ($itemKey === false) {
        return false;
    }
    $methods = $parseArr['methods'] ?: $parseArr['functions'];
    $item = $methods[$itemKey];
    $codeArr = file($parseArr['codefile']);
    $codeArrCount = count($codeArr);
    $blockFirstLineStr = trim($codeArr[$item['docBlockStartLine'] - 1]);
    if ($blockFirstLineStr == '}') {
        $item['docBlockStartLine'] = $item['startLine'];
    }
    if ($blockFirstLineStr == '') {
        $item['docBlockStartLine'] = $item['startLine'];
    }
    $newCode = [];
    for ($i = 0; $i < $item['docBlockStartLine'] - 1; $i++) {
        $newCode[] = $codeArr[$i];
    }
    if ($blockFirstLineStr == '}') {
        $hasSummary = false;
        foreach ($summaryArr as $k => $value) {
            $value = trim($value);
            if ($value) {
                $hasSummary = true;
                break;
            } else {
                unset($summaryArr[$k]);
            }
        }
        if ($hasSummary) {
            array_unshift($summaryArr, LF); // 在前面添加一行
        }
    }
    foreach ($summaryArr as $value) {
        switch (substr(trim($value), 0, 1)) {
            case '/':
                $value = '    ' . trim($value) . "\r\n"; // 加 4 个空格
                break;
            case '*':
                $value = '     ' . trim($value) . "\r\n"; // 加 5 个空格
                break;
        }
        $newCode[] = $value;
    }
    for ($i = $item['startLine'] - 1; $i < $codeArrCount; $i++) {
        $newCode[] = $codeArr[$i];
    }
    file_put_contents($parseArr['codefile'], implode('', $newCode));
    $newParseArr = $that->parsePhpDoc($parseArr['codefile']);
    if ($parseArr['methods']) {
        $parseArr['methods'][$itemKey] = $newParseArr['methods'][$itemKey];
    } else {
        $parseArr['functions'][$itemKey] = $newParseArr['functions'][$itemKey];
    }
    arrayToFile($parseFile, $parseArr);
}
$title = $this->title($type);
$parseDir = $this->parseDir($type);
$fix = $type == 'xmvc' ? 'xmvc_' : '';
if (hasPost()) {
    save($parseFile, $function, $this);
    header('Location: ' . url('self'));
    exit();
}
$allMethods = require($parseDir . "/{$fix}allMethods.php");
$methodsJson = json_encode($allMethods, JSON_UNESCAPED_UNICODE);
$parseArr = require($parseFile);
define('CLASS_NAME', $parseArr['name']);
$classShortName = basename(str_replace('\\', '/', $parseArr['name']));
$methods = $parseArr['methods'] ?: $parseArr['functions'];
$itemKey = getFuncItemKey($parseArr, $function);
if ($itemKey === false) {
    error('没有找到');
}
$item = $methods[$itemKey];
$item['summary'] = isset($item['docBlock']['summary']) ? $item['docBlock']['summary'] : '';
$summaryArr = $this->parseRemark($item['summary']);
$paramString = '<span class="param-name">' . $item['name'] . '</span> ( ' . $this->getParamsString($item['parameters']) . ' ): ';
$paramString .= '<span class="param-return">' . $this->getReturnTypeString($item) . '</span>';
if ($item['isStatic']) {
    $paramString = '<span class="param-static">' . $item['visibility']  . ' static function</span> ' . $classShortName . '::' . $paramString;
} else {
    $paramString = '<span class="blue">' . $item['visibility']  . ' function</span> ' . $paramString;
}
if ($item['abstract']) {
    $abstractFunc = '(抽象方法)';
    $paramString = '<span class="blue">abstract</span> ' .  $paramString;
} else {
    $abstractFunc = '';
}

$paramString = str_replace('"', "'", $paramString);
$tags = $this->parseTags($item);
$tagString = '';
if ($tags) {
    $tagString = '<li>' . implode('</li><li>', $tags) . '</li>';
    $tagString = '<ul class="tag-param">' . $tagString . '</ul>';
}
$codeUrl = HOST . '/xmvc/core/cmd-showPhpCode~filename-' . Encoder::encode($parseArr['codefile']) . '~line-' . $item['startLine'] . '#goto';
$codeArr = file($parseArr['codefile']);
$codeSummaryArr = [];
$blockFirstLineStr = trim($codeArr[$item['docBlockStartLine'] - 1]);
if ($blockFirstLineStr != '}' && $blockFirstLineStr != '') {
    for ($i = $item['docBlockStartLine'] - 1; $i < $item['docBlockEndLine']; $i++) {
        $codeSummaryArr[] = $codeArr[$i];
    }
}
$codeFunctionArr = [];
for ($i = $item['startLine'] - 1; $i < $item['endLine']; $i++) {
    $codeFunctionArr[] = $codeArr[$i];
}

$codeSummaryString = rtrim(implode("", $codeSummaryArr));
$codeFunctionString = rtrim(implode("", $codeFunctionArr));
// @codingStandardsIgnoreStart
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charSet="utf-8" />
    <title><?= $title ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/codemirror.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/theme/dracula.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/codemirror.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/mode/xml/xml.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/mode/javascript/javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/mode/css/css.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/mode/clike/clike.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/mode/php/php.min.js"></script>
    <style>
        <?php require(__DIR__ . '/style.css'); ?>
    </style>
    <?php require(__DIR__ . '/javascript.php'); ?>
    <style>
        .CodeMirror {
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .CodeMirror .CodeMirror-lines {
            font-family: Consolas, monaco, Menlo, Courier, monospace;
            font-size: 14px;
            line-height: 1.5;
        }

        .codeEditor-example .CodeMirror {
            height: auto;
            border: 1px solid #eee;
            padding: 5px 10px;
            background: #FFFFEE;
        }

        .codeEditor-summary .CodeMirror {
            height: auto;
            border: 1px solid #008;
        }


        .codeEditor-source .CodeMirror {
            height: auto;
        }

        .codeEditor-example .cm-comment {
            color: green;
        }

        .codeEditor-summary .cm-comment {
            color: green;
            font-size: 13px;
        }

        .codeEditor-source .cm-comment {
            color: green;
        }
    </style>
    <script>
        document.addEventListener('DOMContentLoaded', (event) => {
            // @example
            var eExample = document.getElementById('codeEditor-example');
            if (eExample) {
                var editorExample = CodeMirror.fromTextArea(eExample, {
                    lineNumbers: false,
                    mode: 'text/x-php',
                    theme: 'default', // 设置主题
                    readOnly: true, // 设置为只读模式            
                });
            }
            var eSummary = document.getElementById('codeEditor-summary');
            if (eSummary) {
                var editorSummary = CodeMirror.fromTextArea(eSummary, {
                    lineNumbers: true, // 显示行号
                    //mode: 'javascript', // 设置代码模式
                    //mode: 'application/x-httpd-php', // 设置代码模式为PHP
                    mode: 'text/x-php',
                    theme: 'default', // 设置主题
                    firstLineNumber: <?= $item['docBlockStartLine'] ?>,
                });
            }
            /*
            var processingInput = false; // 标志位，指示是否正在处理输入
            editor.on('change', function(cm, change) {
                if (!processingInput) { // 如果不是正在处理输入，则进行处理
                    processingInput = true; // 设置正在处理输入标志
                    var lines = cm.getValue().split('\n');
                    var newText = lines.map(function(line) {
                        return line.replace(/ /g, '\u00b7').replace(/\t/g, '\u25b8');
                    }).join('\n');
                    cm.setValue(newText);
                    //processingInput = false; // 清除正在处理输入标志
                }
            });*/
            var eSource = document.getElementById('codeEditor-source');
            if (eSource) {
                var editorSource = CodeMirror.fromTextArea(eSource, {
                    lineNumbers: true,
                    mode: 'text/x-php',
                    matchBrackets: true, // 括号匹配
                    indentUnit: 4, // 缩进单位
                    indentWithTabs: true, // 使用Tab进行缩进
                    theme: 'dracula', //dracula
                    readOnly: true, // 设置为只读模式            
                    firstLineNumber: <?= $item['startLine'] ?>,
                });
            }
        });
    </script>
</head>

<body>
    <div class="div-main">
        <?php require(__DIR__ . '/search.tpl.php'); ?>
        <div class="div-doc">
            <div class="func-header">
                <p><label>命名空间:</label> \<?= $parseArr['namespace'] ?></p>
                <p><label>类名:</label> \<?= $this->gotoClass($parseArr['name']) ?></p>
                <p><label>方法名:</label> <?= $item['name'] ?></p>
                <p><label>源代码:</label> <a href="<?= $codeUrl ?>" class="code-url" target="_blank"><?= $parseArr['codefile'] ?> (<?= $item['startLine'] ?>)</a></p>
            </div>
            <?php if ($summaryArr['title']) echo '<h3><span class="func-title">' . $summaryArr['title'] . '</span></h3>' ?>
            <?php if ($summaryArr['remark']) echo '<p>' . $summaryArr['remark'] . '</p>' ?>
            <p style="font-size:1.2rem;margin:5px 0"><?= $paramString ?></p>
            <?php if ($tagString) echo '<p>' . $tagString . '</p>' ?>
            <div class="codeEditor-summary">
                <form id="form1" action="<?= url('self') ?>" method="post" onsubmit="return confirm('确定要保存当前注释吗？')">
                    <input type="hidden" name='csrf-token' value="<?= getCsrfToken() ?>">
                    <h3 style="color:#080">注释: &nbsp; <input type="submit" value="保存注释"></h3>
                    <textarea id="codeEditor-summary" name="summary"><?= $codeSummaryString ?></textarea>
                </form>
            </div>
            <div class="codeEditor-source">
                <h3 style="color:#888">源代码:</h3>
                <textarea id="codeEditor-source"><?= $codeFunctionString ?></textarea>
            </div>

            <div style="height:100px"></div>
        </div><!-- div-menu -->
    </div><!-- div-main -->
</body>

</html>