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

module.exports = function (re) {
   /* try {
        return new Promise (function (resolve, reject) {
            if ( typeof re !== 'object' || !re.schedules || typeof re.schedules !== 'object' ) {
                throw log.error('bad json geted from: '+ href);
            }

            if ( !fs.existsSync(savedDataPath) ) {
                fs.mkdirSync(savedDataPath);
            }

            if ( re.volume ) {
                log.info('need set global volume to: '+ re.volume);
            } else {
                log.info('no global volume');
            }

            if ( re.schedules.length > 0 ) {
                for ( let i = 1; i <= 7; i++ ) {
                    log.info(moment().add(i, 'days').weekday());
                }

                const todayWeekDayNumber = moment().weekday();
                const getAllowDays = (task) => {
                    if ( task.schedule_day_start === task.schedule_day_end ) {
                        return [ true, true, true, true, true, true, true ];
                    }

                    const allowDaysArr = [
                        false,
                        false,
                        false,
                        false,
                        false,
                        false,
                        false
                    ];
                    const start = (task.schedule_day_start < task.schedule_day_end ? task.schedule_day_start : task.schedule_day_end);
                    const end = (task.schedule_day_start > task.schedule_day_end ? task.schedule_day_start : task.schedule_day_end);

                    for ( let i = start; i <= end; i++ ) {
                        allowDaysArr[i] = true;
                    }

                    return allowDaysArr;
                };
                const getNextRunDatetime = function (task, allowDaysArr) {
                    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;
                };
                const getTimes = (task) => {
                    const re = {};
                    re.startAt = moment(task.schedule_time_start, 'HH:mm');
                    re.diff = Math.round(re.startAt.diff(moment()) / 1000);
                    re.startDate = re.startAt.toDate();
                    re.allowDays = getAllowDays(task);
                    re.nextRunDatetime = getNextRunDatetime(task, re.allowDays);
                    return re;
                };
                let taskWakeup = false;
                let taskShutdown = false;

                re.schedules.forEach((task) => {
                    if ( typeof task !== 'object' || !task.schedule_type || !task.schedule_day_start || !task.schedule_day_end || !task.schedule_time_start || !task.updatedAt  ) {
                        log.error('bad schedule task');
                        return false;
                    }

                    switch ( task.schedule_type ) {
                        case('wakeup'):
                            taskWakeup = task;
                            break;
                        case('reboot'):
                            const reboot = getTimes(task);
                            log.warn('scheduler: reboot on: '+ moment(reboot.nextRunDatetime * 1000).format('DD HH:mm:ss'));
                            nodeSchedule.scheduleJob(moment(reboot.nextRunDatetime * 1000).toDate(), () => childProcess.execFileSync('sudo', ['reboot']));
                            break;
                        case('shutdown'):
                            taskShutdown = task;
                            break;
                        case('update_app'):
                            const updateApp = getTimes(task);
                            log.warn('scheduler: updateApp on: '+ moment(updateApp.nextRunDatetime * 1000).format('DD HH:mm:ss'));
                            ipcMain.emit('scheduler:update_app', updateApp.nextRunDatetime);
                            break;
                        case('update_btn'):
                            const updateButtons = getTimes(task);
                            log.warn('scheduler: updateButtons on: '+ moment(updateButtons.nextRunDatetime * 1000).format('DD HH:mm:ss'));
                            ipcMain.emit('scheduler:update_btn', updateButtons.nextRunDatetime);
                            break;
                    }
                });

                if ( taskWakeup && taskShutdown ) {
                    const now = moment();
                    const wakeupTimes = getTimes(taskWakeup);
                    const taskShutdownTimes = getTimes(taskShutdown);
                    const shutdownAndWakeup = function (wakeupTime) {
                        childProcess.execFileSync('sudo', ['shutdown', '-h', '1']);
                        childProcess.execFileSync('sudo', ['rtcwake', '-m', 'no', '-u', '-t', wakeupTime]);
                    };

                    // log.error('diffs', wakeupTimes.diff, taskShutdownTimes.diff);
                    // log.error('nextRunDatetime', wakeupTimes.nextRunDatetime, taskShutdownTimes.nextRunDatetime);

                    if ( wakeupTimes.diff < taskShutdownTimes.diff ) {
                        if ( wakeupTimes.diff > 300 || !wakeupTimes.allowDays[todayWeekDayNumber] || (taskShutdownTimes.diff < 60 && taskShutdownTimes.allowDays[todayWeekDayNumber]) ) {
                            // shutdown now
                            log.warn('scheduler: shutdown after 1 min and wakeup on: '+ moment(wakeupTimes.nextRunDatetime * 1000).format('DD HH:mm:ss'));
                            shutdownAndWakeup(wakeupTimes.nextRunDatetime);
                        } else {
                            log.warn('scheduler: shutdown on: '+ moment(taskShutdownTimes.nextRunDatetime * 1000).format('DD HH:mm:ss') +' and wakeup on: '+ moment(wakeupTimes.nextRunDatetime * 1000).format('DD HH:mm:ss'));
                            nodeSchedule.scheduleJob(moment(taskShutdownTimes.nextRunDatetime * 1000).toDate(), () => {
                                shutdownAndWakeup(wakeupTimes.nextRunDatetime);
                            });
                        }
                    } else {
                        if ( taskShutdownTimes.diff < 60 && taskShutdownTimes.allowDays[todayWeekDayNumber] && wakeupTimes.diff > 300 ) {
                            // shutdown now
                            log.warn('scheduler: shutdown after 1 min and wakeup on: '+ moment(wakeupTimes.nextRunDatetime * 1000).format('DD HH:mm:ss'));
                            shutdownAndWakeup(wakeupTimes.nextRunDatetime);
                        } else {
                            log.warn('scheduler: shutdown on: '+ moment(taskShutdownTimes.nextRunDatetime * 1000).format('DD HH:mm:ss') +' and wakeup on: '+ moment(wakeupTimes.nextRunDatetime * 1000).format('DD HH:mm:ss'));
                            nodeSchedule.scheduleJob(moment(taskShutdownTimes.nextRunDatetime * 1000).toDate(), () => {
                                shutdownAndWakeup(wakeupTimes.nextRunDatetime);
                            });
                        }
                    }
                }

                fs.writeFileSync(schedulesFilePath, JSON.stringify(re));
            } else {
                log.error('no schedules');
            }

            return resolve();
        });
    } catch (err) {
        log.error('scheduler:parse-schedules', err);
    }*/
};