#!/usr/bin/env php
<?php

/*
 * Author   :    AlicFeng
 * Email    :    a@samego.com
 * Github   :    https://github.com/alicfeng
 * What php team of ev is that is 'one thing, a team, work together'
 */

// 1.CLI 参数处理
$opts = getopt('o:i:');
if (2 != count($opts)) {
    echo "Usage: apidoc-markdown [options...]\n" .
         "-i    input directory  \n" .
         "-o    output directory \n";
    exit(0);
}
list($output, $input) = [$opts['o'], $opts['i']];
if (false === file_exists($input . DIRECTORY_SEPARATOR . 'api_data.json')) {
    echo $input . DIRECTORY_SEPARATOR . 'api_data.json not exists';
    exit(1);
}
$output_dir = $output . DIRECTORY_SEPARATOR . 'documents';
is_dir($output_dir) ? null : mkdir($output_dir, 0777, true);

// 2.加载接口文档数据源数据
$api_data = json_decode(file_get_contents($input . DIRECTORY_SEPARATOR . 'api_data.json'), true);

// 3.定义 sidebar 文件
$sidebar_path = $output . DIRECTORY_SEPARATOR . '_sidebar.md';
file_exists($sidebar_path) ? unlink($sidebar_path) : null;
$sidebar_file = fopen($sidebar_path, 'w');
$sidebar_content = "<!-- docs/_sidebar.md -->\n";

// 4.数据源数据分组
list($group_api_data, $group_name) = [[], 'group'];
foreach ($api_data as $value) {
    $group_api_data[$value[$group_name]][] = $value;
}
unset($api_data);

// 5.遍历分组生成对应的文件
foreach ($group_api_data as $group_name => $api_data) {
    // 5.1假设有生成过了则删除
    $api_doc_markdown_path = $output_dir . DIRECTORY_SEPARATOR . $group_name . '.md';
    file_exists($api_doc_markdown_path) ? unlink($api_doc_markdown_path) : null;

    // 5.2生成 md 文件
    $api_doc_markdown_file = fopen($api_doc_markdown_path, 'w');

    // 5.3处理 sidebar 标题
    $sidebar_content .= '* [' . $group_name . '](documents/' . $group_name . ".md)\n";

    // 5.3编写目录内容 & 处理 sidebar 子标题
    foreach ($api_data as $item_data) {
        fwrite(
            $api_doc_markdown_file,
            '- [x] [' . str_ireplace(' ', '', $item_data['title']) . '](#' . str_ireplace(
                ' ',
                '',
                $item_data['title']
            ) . ")\n"
        );
        $sidebar_content .= '  * [' . $item_data['title'] . '](documents/' . $group_name . '.md#' . str_ireplace(
                ' ',
                '',
                $item_data['title']
            ) . ")\n";
    }

    // 5.4编写主体内容
    foreach ($api_data as $item_data) {
        // dom.title
        fwrite($api_doc_markdown_file, '#### ' . $item_data['title'] . "\n");

        // dom.description
        fwrite($api_doc_markdown_file, '> ' . $item_data['description'] . "\n");

        // dom.method & dom.url
        fwrite($api_doc_markdown_file, "```\n" . $item_data['type'] . '  ' . $item_data['url'] . "\n```\n");

        // dom.header
        if (array_key_exists('header', $item_data)) {
            if (array_key_exists('fields', $item_data['header'])) {
                if (array_key_exists('Header', $item_data['header']['fields'])) {
                    fwrite($api_doc_markdown_file, "\n###### 请求头部\n\n");
                    fwrite(
                        $api_doc_markdown_file,
                        "| 字段 | 类型 | 必选 | 默认值 | 描述 | \n|:----:|:----:|:----:|:----:|:----:|\n"
                    );
                    foreach ($item_data['header']['fields']['Header'] as $field) {
                        fwrite(
                            $api_doc_markdown_file,
                            '| `' . $field['field'] . '` | `' . $field['type'] . '` | ' . ($field['optional'] ? '否' : '是') . ' | ' . $field['defaultValue'] . ' | ' . $field['description'] . " | \n"
                        );
                    }
                }
            }
        }

        // dom.request_parameters
        if (array_key_exists('parameter', $item_data)) {
            if (array_key_exists('fields', $item_data['parameter'])) {
                fwrite($api_doc_markdown_file, "\n###### 请求参数\n\n");
                fwrite($api_doc_markdown_file, "| 字段 | 类型 | 必选 | 描述 | \n|:----:|:----:|:----:|:----:|\n");
                foreach ($item_data['parameter']['fields']['Parameter'] as $field) {
                    fwrite(
                        $api_doc_markdown_file,
                        '| `' . $field['field'] . '` | `' . $field['type'] . '` | ' . ($field['optional'] ? '否' : '是') . ' | ' . $field['description'] . " | \n"
                    );
                }
            }

            //  dom.request_parameters_simples
            if (array_key_exists('examples', $item_data['parameter'])) {
                fwrite($api_doc_markdown_file, "\n###### 请求示例\n\n");
                foreach ($item_data['parameter']['examples'] as $example) {
                    fwrite($api_doc_markdown_file, '- ' . $example['title'] . "\n");
                    fwrite(
                        $api_doc_markdown_file,
                        "```json\n" . json_encode(
                            json_decode($example['content']),
                            JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
                        ) . "\n```\n"
                    );
                }
            }
        }

        if (array_key_exists('success', $item_data)) {
            // dom.response_parameters
            if (array_key_exists('fields', $item_data['success'])) {
                fwrite($api_doc_markdown_file, "\n###### 响应参数\n");
                foreach ($item_data['success']['fields'] as $key => $response_packages) {
                    fwrite($api_doc_markdown_file, "- $key\n\n");
                    fwrite($api_doc_markdown_file, "| 字段 | 类型 | 必选 | 描述 | \n|----|:----:|:----:|:----:|\n");
                    foreach ($response_packages as $field) {
                        fwrite(
                            $api_doc_markdown_file,
                            '| `' . $field['field'] . '` | `' . $field['type'] . '` | ' . ($field['optional'] ? '否' : '是') . ' | ' . $field['description'] . " | \n"
                        );
                    }
                }
            }

            //  dom.success_simples
            if (array_key_exists('examples', $item_data['success'])) {
                fwrite($api_doc_markdown_file, "\n###### 成功响应示例\n\n");
                foreach ($item_data['success']['examples'] as $example) {
                    fwrite($api_doc_markdown_file, '- ' . $example['title'] . "\n");
                    fwrite(
                        $api_doc_markdown_file,
                        "```json\n" . json_encode(
                            json_decode($example['content']),
                            JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
                        ) . "\n```\n"
                    );
                }
            }
        }

        if (array_key_exists('error', $item_data)) {
            if (array_key_exists('examples', $item_data['error'])) {
                //  dom.error_simples
                fwrite($api_doc_markdown_file, "\n###### 失败响应示例\n\n");
                foreach ($item_data['error']['examples'] as $example) {
                    fwrite($api_doc_markdown_file, '- ' . $example['title'] . "\n\n");
                    fwrite(
                        $api_doc_markdown_file,
                        "```json\n" . json_encode(
                            json_decode($example['content']),
                            JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
                        ) . "\n```\n"
                    );
                }
            }
        }

        fwrite($api_doc_markdown_file, "\n\n");
    }

    // 5.5关闭文件
    fclose($api_doc_markdown_file);
}

// 6. sidebar
fwrite($sidebar_file, $sidebar_content) && fclose($sidebar_file);
