import EventBus, { Events, Event } from "../Events/EventBus";
import Utils from "../Utils/Utils";
import UserUtil from "../Utils/UserUtil";
import Player from "./Player";

let instance;
const instanceKey = 'evt_3929942';

class ActivityMonitor {

    _sleepTimeInterval;

    daily_sleep_time;
    daily_sleep_time_enabled;
    MAX_MIN_AHEAD = 1;

    _sleeep_mode_is_on = false;

    constructor(key) {
        if (key !== instanceKey) {
            throw new Error('Cannot instantiate like this')
        }
    }

    init() {
        this.daily_sleep_time_enabled = UserUtil.getUserMetaByKey('daily_sleep_time_enabled', null);
        this.daily_sleep_time_enabled = this.daily_sleep_time_enabled && this.daily_sleep_time_enabled === 'on' ? true : false;

        this._lastActivityTimestamp = Date.now();
        this._handleSleepTime();

        const wakeUp = new Event(
            Events.WAKE_UP,
            (payload) => {
                this._sleeep_mode_is_on = false;
            }
        );
        EventBus.getInstance().registerEvent(wakeUp);
    }

    _handleSleepTime() {

        this._sleepTimeInterval = setInterval(() => {

            if (this._sleeep_mode_is_on) {
                return;
            }

            if (!this.daily_sleep_time_enabled) {
                return;
            }

            if (!Player.getInstance().areSoundsPlaying()) {
                return;
            }
            
            this.daily_sleep_time = UserUtil.getUserMetaByKey('daily_sleep_time', null);
            if (!this.daily_sleep_time) {
                return;
            }
            this.daily_sleep_time_enabled = UserUtil.getUserMetaByKey('daily_sleep_time_enabled', null);
            if (this.daily_sleep_time_enabled !== 'on') {
                return;
            }

            try {
                const [hours, minutes] = this.daily_sleep_time.split(":").map(Number);

                // Get the current time
                const now = new Date();

                // Create a Date object for today at the target time
                const sleepTime = new Date();
                sleepTime.setHours(hours, minutes, 0, 0);

                // Calculate difference in milliseconds
                const diffMs = now - sleepTime;

                // Convert to minutes
                const diffMinutes = diffMs / (1000 * 60);

                if (diffMinutes >= 0 && diffMinutes <= this.MAX_MIN_AHEAD) {
                    this._sleeep_mode_is_on = true;
                    EventBus.getInstance().triggerEvent(
                        Events.GO_TO_SLEEP_MODE, {}
                    );
                }


            } catch (error) {
                console.error(error);
                return;
            }

        }, 9000);
    }


    static getInstance() {
        if (!instance) {
            instance = new ActivityMonitor(instanceKey);
        }
        return instance;
    }
}
export default ActivityMonitor;