const express = require('express')
const fs = require('fs');
const router = express.Router()
const dgram = require('dgram');

let udpResultMsg = ''
// socket 실행
const server = dgram.createSocket('udp4');

server.bind(9400);

server.on('listening',() => {
    console.log('Socket Port : 9400');
});

server.on('message', (msg) => {
    udpResultMsg =  msg.toString();
    console.log('받은 메시지 :',udpResultMsg)

});

server.on('close',() => {
    console.log('Server UDP Socket close');
});


const manager = dgram.createSocket('udp4');
const managerPort= 9300;
const managerHost ='127.0.0.1';

const requestToManager = ((msg) => {
    manager.send(msg, 0, msg.length, managerPort, managerHost, (err) => {
        if ( err ) return ; 
        console.log("UDP send Msg : ",msg)
    });
})

router.get('/', async (req,res)=>{
    
    req.query.image_path = process.env.TEACHING_IMAGE_PATH

    if(req.query.cmd === "neuro_check"){
        req.query.teaching = `${process.env.TEACHING_IMAGE_PATH}-${req.query.project_num}-2-${process.env.TEACHING_RESOLUTION}${req.query.teaching_info}` 
    } 

    requestToManager(JSON.stringify(req.query))

    let requestMsg = ''

    switch(req.query.cmd){

        case "neuro_start":
            requestMsg = 'neuro_start_done'
            break
        case "neuro_ready": 
            requestMsg = 'neuro_ready_done'
            break 
        case "neuro_capture": 
            requestMsg = 'capture_done'
            break 
        case "neuro_check" :
            requestMsg = 'neuro_result'
            break           
        case "neuro_replay" :
            requestMsg = 'btnpush'
            break           
        case "network_check":
            requestMsg = 'network_status'
            break    

        case "neuro_complete":
            requestMsg = 'complete_done'
            break    

        default:
            res.status(404)
    }

    await managerResponse(requestMsg)
        .then(data => {
            res.status(200).json(data)
        })
        .catch(error =>{
            res.status(404).send(error);
        })
})

const managerResponse = ((requestMsg) => {
    return new Promise((resolve, reject) => {
         let delay = 100; //ms 단위로 체크
         let waitingTime = 0 //대기 시간 
        
         let timer = setInterval(() => {            
            if(udpResultMsg.length > 0 && requestMsg === JSON.parse(udpResultMsg).cmd){
                
                 if(requestMsg === 'capture_done'){
                     let base64 = fs.readFileSync('./public/image/capture.jpg' , 'base64')
                     
                     let msg = JSON.parse(udpResultMsg)
                     msg.imageBase64 = base64
                     udpResultMsg = JSON.stringify(msg)
                 }
                 resolve(udpResultMsg)
                 clearInterval(timer)
             }else if(waitingTime === 3_000_000){
                 reject('No response from Manager')
                 clearInterval(timer)
             }else{
                 waitingTime = waitingTime + delay
             }
         },delay)
     });
 })

 manager.on('close',() => {
    console.log('Client UDP socket close')
});

module.exports = router