const API = require("../../../lib/API")
const db = require("../../../plugin/DataBase/db")
const AccessControl = require("../../../lib/AccessControl")
const { BaseStdResponse } = require("../../../BaseStdResponse")

class GetPathDetail extends API {
    constructor() {
        super();

        this.setPath('/Lepao/GetPathDetail')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        let {
            uuid,
            session,
            id
        } = req.query

        if ([uuid, session, id].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER
            })

        // 检查 session
        if (!await AccessControl.checkSession(uuid, session))
            return res.status(401).json({
                ...BaseStdResponse.ACCESS_DENIED
            })

        // 检查权限
        let permission = await AccessControl.getPermission(uuid)
        if (!permission.includes("admin") && !permission.includes("path"))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED
            })

        let sql = `
            SELECT
                id,
                run_zone_name,
                distance,
                point_list,
                time,
                data,
                count,
                speed,
                state
            FROM
                path_data
            WHERE id = ?
        `

        let rows = await db.query(sql, [id])

        if (!rows)
            return res.json({
                ...BaseStdResponse.MISSING_FILE,
                msg: '获取路径数据失败！'
            })

        if(rows.length === 0) 
           return res.json({
                ...BaseStdResponse.MISSING_FILE,
                msg: '路径不存在或已被删除！'
            }) 

        let data = rows[0]
        data.data = data.data.map(point => [point.o, point.a])

        res.json({
            ...BaseStdResponse.OK,
            data
        })
    }
}

module.exports.GetPathDetail = GetPathDetail