console.time('StartUp');
const express = require('express');
var app = express();
const path = require('path');
const http = require('http');
const {Server} = require('socket.io');
const port = process.env.PORT || 5000;
const {Client, GatewayIntentBits,Partials, ActivityType} = require('./lib.js');


app.use(express.static(path.join(__dirname, "public")));
app.set("view engine", "ejs");
app.use(require('cors')())
app.use(express.json());
app.use(express.urlencoded({extended:true}));
// app.use(require('morgan')('dev'))

const mongoDB = process.env.mongoDB;

const server = http.createServer(app);
const io = new Server(server);

const bot = new Client({ intents: [
    GatewayIntentBits.Guilds,  
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildBans,
    GatewayIntentBits.GuildEmojisAndStickers,
    GatewayIntentBits.GuildIntegrations ,
    GatewayIntentBits.GuildWebhooks ,
    GatewayIntentBits.GuildInvites ,
    GatewayIntentBits.GuildVoiceStates,
    GatewayIntentBits.GuildPresences,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.GuildMessageReactions,
    GatewayIntentBits.GuildMessageTyping,
    GatewayIntentBits.DirectMessages,
    GatewayIntentBits.DirectMessageReactions,
    GatewayIntentBits.DirectMessageTyping,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildScheduledEvents,
    GatewayIntentBits.AutoModerationConfiguration,
    GatewayIntentBits.AutoModerationExecution],
    partials: [
        Partials.Reaction,
        Partials.Message 
      ]
}, mongoDB);
var retryCounter = 0;
function login()
{
    bot.login(process.env.discord_token).catch(()=>
    {
        console.log('Server: Failed login', retryCounter)
        if(retryCounter>=900) return startLimitProtectionTimer();
        login();
        retryCounter++;
    });
}
login();
function startLimitProtectionTimer()
{
    console.log('Server: Rate Limit Protection - Sending notification')
    sendNotification('Server Rate Limit Protection - Something broke.');
    setTimeout(() => {
        retryCounter = 0;
        console.log('Server: Rate Limit Protection Reset');
        sendNotification('Nothing was fixed but it will try again.');
        login();
    }, 24*60*60*1000);
}


bot.on('ready', () => 
{
    console.log(`--------------------------\n    ${bot.user.tag.split('#')[0]}   \n          Ready           \n       on `+bot.guilds.cache.size+" guilds         \n    serving "+bot.users.cache.size+" users        \n--------------------------")
    bot.user.setPresence({
        activities: [{ name: `!help`, type: ActivityType.Listening}],
        status: 'online',
    });
    server.listen(port, () => 
    {
        app.use('/', require('./routes/routes')(io, bot));
        console.log(`Http-Server UP`);
    });

    console.timeEnd('StartUp');
    
    setInterval(() => {
        moveAFKs();
    }, 5*60*1000);
});

function moveAFKs(){
    //Gets the members inside the AFK channel
    let auxmembers = bot.channels.cache.get("335494006890823680").members
    //console.log("MoveAFK: Member list with "+ auxmembers.size+" members.")
    //Sorts through them looking for those who have the SS - Secret Services Role
    if(auxmembers.size >0)
    {
        //console.log("hosting:");
    }
    for(var [key, values] of auxmembers){
       //console.log(values.id);;
        if(values.roles.cache.has('693413934715240498')){ 
            //Upon fiding someoe that has said role.           
            //Moves it to the correct Channel.
            values.voice.setChannel('839266096401874974')
                    .then(() => console.log(`MoveAFK: Moved ${values.displayName}.`))
                    .catch(console.error);
        }
    }
}

async function sendNotification(message)
{
    fetch('https://ntfy.wordfights.com/RemChanv2',{
        method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json', 
            },
            body: message
    } )
}