import * as plugins from '../plugins.js';
import { Reception } from './classes.reception.js';
import { logger } from './logging.js';

export class ReceptionHousekeeping {
  public receptionRef: Reception;
  public taskmanager = new plugins.taskbuffer.TaskManager();

  constructor(receptionArg: Reception) {
    this.receptionRef = receptionArg;

    // lets care about old loginsessions
    this.taskmanager.addAndScheduleTask(
      new plugins.taskbuffer.Task({
        name: 'oldLoginSessions',
        taskFunction: async () => {
          logger.log('info', 'running login sessions cleaning task');
          const oneWeekBeforeTimestamp =
            Date.now() - plugins.smarttime.getMilliSecondsFromUnits({ weeks: 1 });
          const oldLoginSessions =
            await this.receptionRef.loginSessionManager.CLoginSession.getInstances({
              data: {
                validUntil: {
                  $lt: oneWeekBeforeTimestamp,
                } as any,
              },
            });
          for (const loginSession of oldLoginSessions) {
            await loginSession.delete();
          }
          logger.log('info', `Completed deletion of ${oldLoginSessions.length} old loginSessions`);
        },
      }),
      '2 * * * * *'
    );

    this.taskmanager.start();
    logger.log('info', 'housekeeping started');
  }

  public async stop() {
    this.taskmanager.stop();
    logger.log('info', 'housekeeping stopped');
  }
}
