// tslint:disable:no-console
import * as moment from 'moment-timezone';
import * as mongoose from 'mongoose';

import { chevre } from '../../../../lib/index';

async function main() {
    await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });

    const assetTransactionRepo = await chevre.repository.AssetTransaction.createInstance(mongoose.connection);
    const projectRepo = await chevre.repository.Project.createInstance(mongoose.connection);

    const aggregateDate = new Date();
    // const aggregateDurationUnit = 'days';
    // const startFrom: Date = moment(aggregateDate)
    //     .utc()
    //     .startOf(aggregateDurationUnit)
    //     .toDate();
    // const startThrough: Date = moment(aggregateDate)
    //     .utc()
    //     .endOf(aggregateDurationUnit)
    //     .toDate();
    const startThrough: Date = aggregateDate;
    const startFrom: Date = moment(aggregateDate)
        .add(-1, 'days')
        .toDate();

    const cursor = projectRepo.getCursor(
        {
            _id: { $nin: ['xxx'] }
        },
        {
            _id: 1
        }
    );
    console.log('docs found');

    let i = 0;
    let results: {
        id: string;
        reservationCount?: number;
    }[] = [];
    await cursor.eachAsync(async (doc) => {
        i += 1;
        const project: Pick<chevre.factory.project.IProject, 'id'> = doc.toObject();

        const startTime = process.hrtime();
        const aggregateResult = await assetTransactionRepo.aggregateAssetTransaction({
            project: { id: { $eq: project.id } },
            startFrom,
            startThrough,
            typeOf: chevre.factory.assetTransactionType.Reserve
        });
        const reservationCount = aggregateResult.statuses.find(
            ({ status }) => status === chevre.factory.transactionStatusType.Confirmed
        )?.aggregation.reservationCount;
        console.log(
            'reservationCount',
            reservationCount,
            project.id,
            startFrom, startThrough
        );
        const diff = process.hrtime(startTime);
        console.log(`took ${diff[0]} seconds and ${diff[1]} nanoseconds.`);
        results.push({ id: project.id, reservationCount });
    });

    results = results.sort(
        (a, b) => {
            return Number(b.reservationCount) - Number(a.reservationCount);
        });
    console.log(results);
}

main()
    .then(() => {
        console.log('success!');
    })
    .catch(console.error);
