const strftime = require('strftime');
const database = require(`${appPath}/lib/database`);
const UserException = require(`${appPath}/lib/exceptions/userException`);

module.exports = {
    name: 'rpt-zone',
    async asyncData(ctx, params) {
        if (!params.routeFk)
            throw new UserException('No route id specified');

        let [[zone]] = await this.methods.fetchRoute(params.routeFk);

        if (!zone)
            throw new UserException('Route not ready');

        return {zone};
    },
    methods: {
        fetchRoute(routeFk) {
            return database.pool.query(
                `SELECT
                    r.id,
                    r.time,
                    am.name agencyName,
                    v.numberPlate plateNumber
                FROM route r
                    JOIN agencyMode am ON am.id = r.agencyModeFk
                    JOIN vehicle v ON v.id = r.vehicleFk
                WHERE r.id = ?`, [routeFk]);
        },
        zoneTime: zoneTime => {
            if (zoneTime)
                return strftime('%H:%M', zoneTime);
        },
    },
};