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

exports.data = async (req,res,next) => {
	let {start,end} = req.body;
	const condition = {'$and': [{'createdAt': {'$gte': moment(start, 'YYYYMMDD').startOf('day').toDate()}}, {'createdAt': {'$lt': 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 upstream.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({});
    const adminPromise =  await upstream.count({ creater:mongoose.Types.ObjectId('58afdd80aa96916a41598698') });
    let userCount= 0;
    let upstreamCount = 0;
    let adminCount = 0;
    await Promise.all([userPromise,upstreamPromise,adminPromise]).then( ([users,upstreams,admin]) => {
    	userCount = users;
    	upstreamCount = upstreams;
        adminCount = admin;
    });
    res.send({result: 'ok' ,data: {user: userCount, upstream: upstreamCount, admin: adminCount}})

}



exports.detail = async(req,res,next) => {
    let { limit = 30 , skip = 0} = req.body;
    try{ 
        const users = await user.find({},null,{limit: parseInt(limit),skip: parseInt(skip)*30}).sort({createdAt: -1});
        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:parseInt(skip),total: total, pageSize:parseInt(limit)}}})
    } catch ( err ) {
        console.dir(err);
        res.status(400);
    }
}