/* eslint-disable no-undef */
import { TextChannel } from 'eris';
import { Client, RichEmbed } from '../class';
import { CloudServicesUtil } from '../util';

let interval: NodeJS.Timeout;

export default async function checkLock(client: Client) {
  async function start() {
    try {
      const moderations = await client.db.mongo.Moderation.find();
      const judgements = await client.db.mongo.Judgement.find().lean().exec();
      const members = await client.db.mongo.Member.find();
      members.forEach(async (member: typeof members[0]) => {
        if (member.misc?.t3TemporaryExpiration && member.misc.t3TemporaryExpiration.processed === false) {
          if (new Date() > member.misc.t3TemporaryExpiration.date) {
            await CloudServicesUtil.setTier(member.userID, member.misc.t3TemporaryExpiration.previousTier, client.config.internalKey);
            await member.updateOne({ 'misc.t3TemporaryExpiration.processed': true, 'misc.t3TemporaryExpiration.previousTier': null });
          }
        }
      });
      judgements.forEach(async (judgement) => {
        if (!judgement.expires) return;
        if (new Date() > judgement.expires) {
          await client.db.mongo.Judgement.deleteOne(({ _id: judgement._id }));
          const log = <TextChannel> client.guilds.get(client.config.guildID).channels.get('611584771356622849');
          const embed = new RichEmbed();
          embed.setTitle('Judgement - Rescind');
          embed.addField('Member', `<@${judgement.userID}>`, true);
          embed.addField('Rescinded by', 'SYSTEM', true);
          embed.setFooter(client.user.username, client.user.avatarURL);
          embed.setTimestamp();
          log.createMessage({ embed }).catch(() => {});
        }
      });
      moderations.forEach(async (moderation) => {
        if (!moderation.expiration) return;
        if (moderation.expiration.processed) return;
        if (new Date() > moderation.expiration.date) {
          await moderation.updateOne({ 'expiration.processed': true });

          const system = client.guilds.get(client.config.guildID).members.get(client.user.id);
          switch (moderation.type) {
            case 5:
              await client.util.moderation.unban(moderation.userID, system);
              break;
            case 2:
              if (await client.db.local.muted.get<boolean>(`muted-${moderation.userID}`) === true) {
                await client.util.moderation.unmute(moderation.userID, system);
              }
              break;
            default:
              break;
          }
          client.util.signale.complete(`Released member ${moderation.userID} | Queue date at ${moderation.expiration.date.toLocaleString('en-us')}`);
        }
      });
    } catch (error) {
      await client.util.handleError(error);
    }
  }
  await start();
  interval = setInterval(async () => {
    await start();
  }, 10000);
  return interval;
}
