import express from 'express'
import UserM from '../models/user'

export class UserController{
    login = (req: express.Request, res: express.Response)=>{
        let u = req.body.username;
        let p = req.body.password;

        UserM.findOne({username: u, password: p}).then((user)=>{
            res.json(user)
        }).catch((err)=>{
            console.log(err)
            res.json(null)
        })
    }

    register = (req: express.Request, res: express.Response)=>{
        let username = req.body.username;
        let password = req.body.password;
        let firstname = req.body.firstname;
        let lastname = req.body.lastname;

        let user = {
            username: username,
            password: password,
            firstname: firstname,
            lastname: lastname
        }

        new UserM(user).save().then(ok=>{
            res.json({message: "ok"})
        }).catch(err=>{
            console.log(err)
            res.json({message: "fail register"})
        })
    }

    addToFavourites= (req: express.Request, res: express.Response)=>{
        let dateNow = new Date();
        let dateStr = dateNow.getFullYear() + "-" + (dateNow.getMonth()+1) + "-" + dateNow.getDate();
        let fav = {
            name: req.body.name,
            author: req.body.author,
            date: dateStr
        }
        UserM.updateOne({username: req.body.user}, {$push: {favourites: fav}}).then(data=>{
                res.json({message: "Ok"})
            }).catch(err=>{
                res.json({message: "Fail"})
            })
    }

    deleteFromFavourites = (req: express.Request, res: express.Response)=>{
        let name = req.body.book
        let user = req.body.user
        UserM.updateOne({username: user}, 
            {$pull: {favourites: {name: name}}}).then(data=>{
                res.json({message: "Ok"})
            }).catch(err=>{
                res.json({message: "Fail"})
            })
    }

    updateFavourite = (req: express.Request, res: express.Response)=>{
        let name = req.body.book
        let user = req.body.user

        UserM.updateOne({username: user}, {$set: {"favourites.$[fav].name": "New fav changed"}}, {arrayFilters: [{
            "fav.name": name
        }]}).then(data=>{
            res.json({message: "Ok"})
        }).catch(err=>{
            res.json({message: "Fail"})
        })
    }

    getUser = (req: express.Request, res: express.Response)=>{
        let user = req.params.user
        // UserM.findOne({_id: "6588537a44a71c2c6f674495"}).then(user=>{
        //         res.json(user).status(200)
        // }).catch(err=>{
        //         res.json({message: "Fail"}).status(400)
        // })

        UserM.findOne({username: user}).then(user=>{
                res.json(user).status(200)
        }).catch(err=>{
                res.json({message: "Fail"}).status(400)
        })
    }
}