const express = require('request-promise');
const user = require('../db/mongo/user');
const upstream = require('../db/mongo/upstream');
const moment = require('moment');

exports.data = async (req,res,next) => {
	let {start,end} = req.body;
	const condition = {'$and': [{'createdAt': {'$gte': moment(start, 'YYYYMMDD').startOf('day').toDate()}}, {'createdAt': {'$lte': moment(end, 'YYYYMMDD').endOf('day').toDate()}}]};
	const basicCondition = {'createdAt': {'$lt': moment(start, 'YYYYMMDD').startOf('day').toDate()}};
	console.dir(condition['$and']);
	console.dir(basicCondition);
	const pipeline = [
        {'$match': condition},
        {'$project':
        	{
		        "year": { "$year": { "$add": [ "$createdAt", 8 * 60 * 60 * 1000 ] } }, 
		        "month": { "$month": { "$add": [ "$createdAt", 8 * 60 * 60 * 1000 ] } }, 
		        "day": { "$dayOfMonth": { "$add": [ "$createdAt", 8 * 60 * 60 * 1000 ] } } 
		    }
		},
        {
            '$group': {
                _id:{ month: '$month', day:'$day', year:'$year'},
                count: {$sum: 1}
            }
        }
    ];

    const userPromise = await user.aggregate(pipeline);
    const basicUserPromise = await user.count(basicCondition);
    const upstreamPromise =  await upstream.aggregate(pipeline);
    const basicUpstreamPromise = await user.count(basicCondition);

    let userResult = [];
    let upstreamsResult = [];
    let userCount = 0;
    let upCount = 0;
    await Promise.all([userPromise,basicUserPromise,upstreamPromise,basicUpstreamPromise]).then( ([users,userCon,upstreams,upCon]) => {
    	userResult = users;
    	upstreamsResult = upstreams;
    	userCount = userCon;
    	upCount = upCon;
    });
	res.send({result: 'ok' ,data: {userCount: userCount, upCount: upCount, users: userResult, upstreams: upstreamsResult, range:[start,end]}})
};

exports.count = async(req,res,next) => {

	const userPromise = await user.count({});
    const upstreamPromise =  await upstream.count({});
    let userCount= 0;
    let upstreamCount = 0;
    await Promise.all([userPromise,upstreamPromise]).then( ([users,upstreams]) => {
    	userCount = users;
    	upstreamCount = upstreams;
    });
    res.send({result: 'ok' ,data: {user: userCount, upstream: upstreamCount}})

}



exports.detail = async(req,res,next) => {
    let { limit = 3 , skip = 0} = req.body;
    try{ 
        const users = await user.find({},null,{limit: limit,skip: skip});
        const total = await user.count({},null);
        let creaters = [];
        users.forEach( item => {
            creaters.push(item['_id'])
        });
        const pipeline = [
            {'$match': { creater: {'$in': creaters} }},
            {
                '$group': {
                    _id:{ creater: '$creater' },
                    count: { $sum: 1 }
                }
            }
        ];
        const upstreams =  await upstream.aggregate(pipeline);
        res.send({result: 'ok' ,data: { users: users.map(x => x.toJSON()), upstreams: upstreams, pagination:{ current:skip,total: total, pageSize:limit}}})
    } catch ( err ) {
        console.dir(err);
        res.status(400);
    }
}