'use strict';

/**
 * Module dependencies.
 */
const mongoose = require('mongoose'),
  express = require('express'),
  http = require('http'),
  bodyParser = require('body-parser'),
  methodOverride = require('method-override'),
  cookieParser = require('cookie-parser'),
  app = express(),
  router = express.Router(),
  db = mongoose.connect('mongodb://172.29.0.102:27017/familyark', { useMongoClient: true }),
  user = require('./model/user')(db),
  animal = require('./model/animal')(db),
  species = require('./model/species')(db),
  host = '172.29.0.101',
  port = 3000,
  request = require('request')

http.createServer(app)

router.get('/species', (req, res, next) => {
    species.find({}, (err, result) => {
        if (err) next(err)
        else res.json({ data: result,  status: 'ok' })
    })
})

router.get('/animal', (req, res, next) => {
    animal.find({}, (err, result) => {
        if (err) next(err)
        else res.json({ data: result,  status: 'ok' })
    })
})

router.get('/animal/childrens/:id', (req, res, next) => {
    animal.find({ $or: [ { father: req.params.id }, { mother: req.params.id } ] }, (err, result) => {
        if (err) next(err)
        else res.json({ data: result,  status: 'ok' })
    })
})

router.get('/animal/parrents/:id', (req, res, next) => {
    animal.find({ _id: req.params.id }, (err, result) => {
        if (err) next(err)
        else animal.find({ $or: [ { _id: result[0].father }, { _id: result[0].mother } ] }, (err, result2) => {
            if (err) next(err)
            else res.json({ data: result2,  status: 'ok' })
        })
    })
})

router.get('/animal/:id', (req, res, next) => {
    animal.find({ _id: mongoose.Types.ObjectId(req.params.id) }, (err, result) => {
        if (err) next(err)
        else res.json({ data: result[0],  status: 'ok' })
    })
})

router.get('/animal/:specie/:sex', (req, res, next) => {
    animal.find({ specie: req.params.specie, sex: req.params.sex}, (err, result) => {
        if (err) next(err)
        else res.json({ data: result,  status: 'ok' })
    })
})

router.post('/animal', (req, res, next) => {
    let s1 = new animal(req.body)
    s1.save((err, doc) => {
	if (err) next(err)
        else res.json(doc)
    })
})

router.put('/animal/:id', (req, res, next) => {
    animal.findOneAndUpdate({_id: mongoose.Types.ObjectId(req.params.id)}, req.body, {upsert: true}, (err, doc) => {
        if (err) next(err)
        else res.json(doc)
    })
})

router.delete('/animal/:id', (req, res, next) => {
    animal.findOneAndRemove({ _id: mongoose.Types.ObjectId(req.params.id) }, (err) => {
        if (err) next(err)
        else res.json({ status: 'ok' })
    });
})


router.get('/info', (req, res, next) => {
    request('http://arkdedicated.com/dynamicconfig.ini', function (error, response, body) {
        var acc = {}
        body.split("\n").map( (x) => { 
            let d = x.split("=")
            acc[d[0]] = d[1]
        })
        res.json(acc)
    });
})

/*function recu(acc,item){
	if(item.mather != null){
	    animal.find({ _id: mongoose.Types.ObjectId(item.mother) }, (err, result) => {
        	if (err) next(err)
	        else {acc.push(result[0]); recu(acc,result[0])}
	    })
	}

};
*/
// router.get('/animal/tree/:id', (req, res, next) => {
// /*    animal.find({ _id: mongoose.Types.ObjectId(req.params.id) }, (err, result) => {
//         if (err) next(err)
//         else res.json(recu([],result[0]))
//     })
// */
//     animal.aggregate([{ $match: { _id: mongoose.Types.ObjectId(req.params.id) }},
//         { $graphLookup: { from: 'animals', startWith: ['$father', '$mother'], connectFromField: 'mother', connectToField: '_id', as: 'ancestorsmother', maxDepth: 99, depthField: 'depth' }},
//         { $graphLookup: { from: 'animals', startWith: ['$father', '$mother'], connectFromField: 'father', connectToField: '_id', as: 'ancestorsfather', maxDepth: 99, depthField: 'depth' }},
//         { $graphLookup: { from: 'animals', startWith: '$_id', connectFromField: '_id', connectToField: 'mother', as: 'childrensmother', maxDepth: 99, depthField: 'depth' }},
//         { $graphLookup: { from: 'animals', startWith: '$_id', connectFromField: '_id', connectToField: 'father', as: 'childrensfather', maxDepth: 99, depthField: 'depth' }},
//         { $project: { 'name': 1, 'sex': 1, 'father': 1, 'mother': 1, ancestors: { $setUnion: ['$ancestorsmother', '$ancestorsfather'] }, childrens: { $setUnion: ['$childrensmother', '$childrensfather'] }}
//         }]).allowDiskUse(true).exec((err, connections) => {
//         if (err) next(err)
//         else res.json(connections)
//     })
// })

app.use(bodyParser.urlencoded({
  extended: true
}))
.use(bodyParser.json())
.use(methodOverride())
.use(cookieParser())
.use(router)
.use(express.static('public')).listen(port, host, () => {
  console.log(`Listening on: ${host}:${port}`)
})

