const router = require('express').Router()
const { promisify } = require('util')
const jwt = require('jsonwebtoken')
const fs = require('fs')
const path = require('path')
const md5 = require('crypto-js/md5')

const { JWT_SECRET_KEY } = require('./constants')
const { getResponse } = require('../../../utils/common')
const { connect, getPeoplesData, createDept, getDepts, getDeptData, deleteDeptById, setUsers, authenticate } = require('./controllers')

connect()

router.get('/depts', async (req, res) => {
    const errors = []
    const depts = await getDepts().catch((e) => errors.push(e.message))
    res.send(getResponse(errors, depts))
})

router.get('/peoples', async (req, res) => {
    const errors = []
    const peoplesData = await getPeoplesData().catch((e) => errors.push(e.message))
    res.send(getResponse(errors, peoplesData))
})

router.post('/depts/create', async (req, res) => {
    const errors = []
    const deptData = await createDept(req.body.data).catch((e) => errors.push(e.message))
    res.send(getResponse(errors, deptData))
})

router.get('/dept/:id', async (req, res) => {
    const errors = []
    const data = await getDeptData(req.params.id)
    res.send(getResponse(errors, data))
})

router.post('/dept/delete', async (req, res) => {
    const errors = []
    await deleteDeptById(req.body)
    res.send(getResponse(errors, 'success'))
});

router.post('/login', async (req, res, next) => {
    const auth = promisify(authenticate)
    try {
        console.log(req.body.login)
        console.log(req.body.password)
        const { hash, salt, ...user } = await auth(req.body.login, req.body.password)

        const token = jwt.sign({
            user,
        }, JWT_SECRET_KEY)
        req.session.regenerate(() => {
            req.session.user = user
            res.send({
                success: true,
                body: {
                    ...user,
                    token,
                },
                errors: [],
                warnings: [],
            })
        })
    } catch (error) {
        next(error)
    }
})

router.get('/tasks', (req, resp) => {
    resp.send(require('./stubs/tasks/tasks.json'))
})

router.post('/tasks/create', (req, resp) => {
    try {
        const { dept } = req.body
        const rawTasksData = fs.readFileSync(path.resolve(__dirname, './stubs/tasks/tasks.json'))
        const tasksData = JSON.parse(rawTasksData)
        const deptTasksData = tasksData.body.filter((data) => data.label === dept)

        const task = {
            id: md5(new Date()).toString(),
            number: 100,
            task: req.body.task,
            status: 'open',
            priority: req.body.priority,
            performer: req.body.performer,
            deadline: new Date(req.body.deadline).getTime(),
            lastChanged: new Date().getTime(),
            description: req.body.description,
        }

        if (!deptTasksData.length) {
            const newDeptTasksData = {
                label: req.body.dept,
                data: [task],
            }
            tasksData.body.push(newDeptTasksData)
        } else {
            tasksData.body.map((data) => {
                if (data.label === dept) {
                    return data.data.push(task)
                }
                return data
            })
        }
        fs.writeFileSync(path.resolve(__dirname, './stubs/tasks/tasks.json'), JSON.stringify(tasksData))
        resp.send({
            success: true,
            body: task,
            errors: [],
            warnings: [],
        })
    } catch (e) {
        resp.send('./stubs/error.json')
    }
})

router.post('/tasks/delete', (req, resp) => {
    resp.send(require('./stubs/tasks/delete.json'))
})

router.post('/tasks/edit', (req, resp) => {
    resp.send({
        success: true,
        body: req.body,
        errors: [],
        warnings: [],
    })
})

router.post('/sign-up', async (req, res, next) => {
    try {
        const { hash, salt, ...user } = await setUsers({
            login: req.body.login,
            password: req.body.password,
            mail: req.body.mail,
        })

        const token = jwt.sign({
            user,
        }, JWT_SECRET_KEY)
        req.session.regenerate(() => {
            req.session.user = user

            res.send({
                success: true,
                body: {
                    ...user,
                    token,
                },
                errors: [],
                warnings: [],
            })
        })
    } catch (error) {
        next(error)
    }
})

module.exports = router
