const config = require('./config.json')

const io = require("socket.io-client")
const axios = require('axios')
const fs = require('fs')

function filter(txt) {
    if (txt.length > 240) txt = txt.substring(0, 240)
    return txt.replace(/[^\x00-\x7F]/g, "")
}


function editStatus(msgId, msg) {
    if (!assoc[msgId]) return
    const sPass = Math.floor( (new Date().valueOf() - assoc[msgId].date.valueOf() ) / 1e3)
    msg = `+${ sPass }s> ${ msg }`

    console.log(assoc[msgId])
    const [tgChatId, tgMsgId] = [assoc[msgId].tgchat, assoc[msgId].tgmsg]
    assoc[msgId].newText = assoc[msgId].newText + '\n' + msg
    console.log(assoc[msgId])
    bot.telegram.editMessageText(tgChatId, tgMsgId, null, assoc[msgId].newText).then(console.log)
}
/*
socket.on('msgmgr:event', (eventType, eventData) => {
    console.log(eventType, eventData)
    switch (eventType) {
        case 'status': {
            const [msgId, uuid, status] = eventData
            editStatus(msgId, `${ uuid } is ${ status }`)
        } break;
        case 'read':
            editStatus(eventData, 'read')
        break;
        case 'response': {
            const [msgId, response] = eventData
            editStatus(msgId, 'response ' + response)
        } break;
    }
})
bot.on('message', (ctx) => {
    if (!ctx.update.message.text) return ctx.reply("not a textmessage")
//    if (!ctx.update.message.type)
    console.log(ctx.update.message.from)
    const preview = `Preview: ${ filter(ctx.update.message.from.first_name) }:${ filter(ctx.update.message.text) }`
    console.log(preview)
    ctx.reply(preview, Markup.inlineKeyboard(
        config.deliveryModes.map((deliveryModeConfig, index) => 
            Markup.button.callback(deliveryModeConfig.name, 'deliveryMode-' + index)
        )
    ))
})

for (let deliveryModeIndex in config.deliveryModes) {
    bot.action('deliveryMode-' + deliveryModeIndex, async (ctx) => {
        const origText = ctx.update.callback_query.message.text.substring(8+1)
        await ctx.answerCbQuery()
        await ctx.editMessageReplyMarkup(undefined)

        const deliveryModeData = config.deliveryModes[ deliveryModeIndex ]

        let msgId = (
            await axios.post(
                new URL(config.pager.url).origin + '/api/message/' + (!!deliveryModeData.preset ? 'preset' : 'advanced'),
                Object.assign( !!deliveryModeData.preset
                    ? { preset: deliveryModeData.preset } // backward compatibility
                    : { ...deliveryModeData.params }
                , {
                    payload: origText
                })
            )
        ).data
        assoc[msgId] = {
            date: new Date(),
            tgmsg: ctx.update.callback_query.message.message_id,
            text: origText,
            newText: `Preview: ${ origText }\n\n--[${ msgId }]--\n`,
            tgchat: ctx.update.callback_query.message.chat.id
        }
        await ctx.editMessageText(assoc[msgId].newText)
    })
}
*/
const express = require('express')
const { query } = require('express')


const app = express()
app.use(express.json())
app.use(express.static('html_public'))
app.use(express.static(__dirname + '/node_modules/@mdi/font'))

const allowedIDs = []

app.get('/api/modes', async (req, res) => {
    return res.json(config.deliveryModes)
})
app.get('/api/devices', async (req, res) => {
    const devices = (await axios.get(new URL(config.pager.url).origin + '/api/devices')).data
    Object.keys(devices).map(key => {
        devices[ key ].lastLoRaPacket = !!devices[ key ].lastLoRaPacket 
            ? {
                received_at: devices[ key ].lastLoRaPacket.received_at,
            } : null
    })
    return res.json(devices)
})
app.get('/api/message/status', async (req, res) => {
    if (!req.query.ids) return res.status(500).json("ERROR: no ids")
    const queryIDs = req.query.ids
    if (queryIDs.length > 3) queryIds = queryIDs.slice(0,3)
    let results = []
    for (let msgID of queryIDs) {
        if (allowedIDs.indexOf(msgID) > -1)
            try {
                let msgStatus = (
                    await axios.get(new URL(config.pager.url).origin + '/api/message/status/' + msgID)
                ).data

                if (!!msgStatus._routerData && !!msgStatus._routerData.metadata) {
                    msgStatus._routerData.metadata = msgStatus._routerData.metadata.map(x => {
                        if (x.ack == 'operational') {
                            try {
                                x.operationalData = x.metadata.uplink_message.decoded_payload.operationalData
                            } catch (ee) {}
                        }
                        delete x.metadata
                        return x
                    })
                }
                results.push(msgStatus)
            } catch (e) {
            }
    }
    return res.json(results)
})
app.post('/api/message/preset', async (req, res) => {
    if (!req.body.preset) return res.status(500).json("ERROR: no msg preset")
    if (!req.body.payload) return res.status(500).json("ERROR: no msg payload")

    if (config.deliveryModes.filter(a=>a.preset == req.body.preset).length !== 1) return res.status(500).json("ERROR: mode does not exist")
    
    let msgId = (
        await axios.post(config.pager.url, { preset: req.body.preset, payload: req.body.payload })
    ).data
    allowedIDs.push(msgId)
    return res.json(msgId)
})
app.listen(3091, '0.0.0.0' || config.host || '127.0.0.1')

const appConfig = express()
appConfig.use(express.json())
appConfig.use(express.static('html_config'))
appConfig.use(express.static(__dirname + '/node_modules/@mdi/font'))

/** CONFIG Routes */

appConfig.get('/config', async (req, res) => {
    return res.json(JSON.parse(fs.readFileSync('config.json')))
})
appConfig.get('/api/deliveryPresets', async (req, res) => {
    const presets = await axios.get(new URL(config.pager.url).origin + '/api/deliveryPresets')
    return res.json(presets.data)
})
appConfig.post('/config', async (req, res) => {
    if (!(!!req.body.deliveryModes)) return res.status(403).json(false)
    if (!(!!req.body.pager)) return res.status(403).json(false)
    console.log(req.body)
    fs.writeFileSync('config.json', JSON.stringify(req.body, null, "\t"))
    return res.json(true)
})
appConfig.post('/restart', (req, res) => {
    process.exit(1)
})

appConfig.listen(3090, '0.0.0.0' || config.host || '127.0.0.1')

