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

router.get('/',async (req,res) => {
    const project = JSON.parse( fs.readFileSync('./json/project.json').toString() )
    const learning = JSON.parse( fs.readFileSync('./json/learning.json').toString() )

    let result = {
        'project':project,
        'learning':learning
    }

    res.send(result) 
})

router.post('/',async (req,res) => {
    const project = JSON.parse( fs.readFileSync('./json/project.json').toString() )
    const learning = JSON.parse( fs.readFileSync('./json/learning.json').toString() )

    // 받아온 값이 있을경우
    if(Object.keys(req.body).length !== 0 ){
        project.admin = req.body.project.admin
        project.aoiUid = req.body.project.aoiUid
        project.counter = req.body.project.counter
        project.createDate = req.body.project.createDate
        project.name = req.body.project.name
        project.state = req.body.project.state
        project.successDate = req.body.project.successDate
        project.uid = req.body.project.uid
        project.user = req.body.project.user
        project.updateDate = new Date()
        project.total = req.body.project.total 
        project.success = req.body.project.success
        project.fail = req.body.project.fail
        project.result = req.body.project.result

        learning.learning = req.body.learning

        fs.writeFileSync('./json/project.json',JSON.stringify(project) , (err) =>{
            if ( err ) return err; 
        })
        fs.writeFileSync('./json/learning.json',JSON.stringify(learning) , (err) =>{
            if ( err ) return err; 
        })

    }else{
        fs.writeFileSync('./json/project.json',JSON.stringify({}) , (err) =>{
            if ( err ) return err; 
        })

        fs.writeFileSync('./json/learning.json',JSON.stringify({}) , (err) =>{
            if ( err ) return err; 
        })
    }

    let result = {
        'project':project,
        'learning':learning.learning
    }

    res.status(200).send(result)
})

module.exports = router