const fs = require('fs');
const ftp = require('ftp');
const path = require('path');
const client = new ftp();

function changeMD(url) {
    var str = ''
    if (url.indexOf('s2c') != -1) {
        str = `
## [返回上一级](README.md)

## 目录

        `
    } else if (url.indexOf('s2o') != -1) {
        str = `
## [返回上一级](README.md)
## 通用说明

- 所有请求方法均为 \`POST\`
- 所有请求均需加入以下 Header :
    - \`Content-Type: application/json\`
- 调用api的格式为:
    - \`url: http://{ip}:{port}{path}\`
    - \`body: 对应api的请求类型\`
    - \`加密方式: 联系该项目的后端获取\`
- 返回值统一为:
    - 请求参数校验不成功返回：
        - \`data error 字符串\`
    - 请求参数校验成功:
            {
                /**请求是否成功 */
                isSucc: boolean;
                /**请求的返回值 对应调用api的响应值*/
                res?: any;
                /**请求返回的错误信息*/
                err?: any;
            }
- 以向玩家发送邮件为例:

    ![发送邮件代码示例](../../img/heijiao_http_api_send.png)
    ![发送邮件代码示例](../../img/heijiao_http_api_send_over.png)

## 目录
        `
    }

    let file = fs.readFileSync(url, 'utf-8');
    file = file.replace(/^# TSRPC API 接口文档(.|\n)*^## 目录/gm, str);
    fs.writeFileSync(url, file);
}

changeMD('doc/s2c/tsapi.md');
changeMD('doc/s2o/tsapi.md');

client.on('ready', async () => {
    console.log('ftp client is ready');

    await cd('document/serverDoc/doc/heijiao');
    let { err, files } = await list();
    console.log(files);
    for (let file of files) {
        await del(file.name)
    }
    await put('doc/s2c/tsapi.md', 's2c.md');
    await put('doc/s2o/tsapi.md', 's2o.md');

    client.destroy();
});

client.on('close', () => {
    console.log('ftp client has close')
});

client.on('end', () => {
    console.log('ftp client has end')
});

client.on('error', (err) => {
    console.log('ftp client has an error : ' + JSON.stringify(err))
});

client.connect({
    host: '10.0.1.20',
    port: '21',
    user: 'administrator',
    password: ']v)CnD~r|yl[7??22uTI',
    keepalive: 1000
});

//列出目标目录
async function list() {
    return new Promise((resolve, reject) => {
        client.list((err, files) => {
            resolve({ err: err, files: files });
        })
    });
}

//切换目录
async function cd(dirPath) {
    return new Promise(res => {
        client.cwd(dirPath, (err, dir) => {
            res({ err: err, dir: dir })
        })
    });
}

//删除
async function del(path) {
    return new Promise(res => {
        client.rmdir(path, (err, dir) => {

            res({ err: err, dir: dir })
        })
    });
}

//将文件上传到ftp目标地址
async function put(currentFile, targetFilePath) {
    const rs = fs.createReadStream(currentFile);

    return new Promise((resolve, reject) => {
        client.put(rs, targetFilePath, (err) => {
            resolve({ err: err });
        })
    });
}