const moment = require('moment');
const log = require('electron-log');

module.exports = (task, allowDaysArr) => {
    try {
        const todayWeekDayNumber = moment().weekday();
        const startAt = moment(task.schedule_time_start, 'HH:mm');
        const diff = Math.round(startAt.diff(moment()) / 1000);
        let startDate = startAt.unix();

        if ( diff <= 0 || !allowDaysArr[todayWeekDayNumber] ) {// get next allow datetime
            for ( let i = 1; i <= 7; i++ ) {
                const day = startAt.add(i, 'day');

                if ( allowDaysArr[day.weekday()] ) {
                    startDate = day.unix();
                    break;
                }
            }
        }// else allow today

        return startDate;
    } catch (err) {
        log.error('scheduler:get-next-run-datetime', err);
    }
};
