/** 
 * Simulates visits from the moderator
 */

const puppeteer = require("puppeteer");

// TODO: change to NODE_ENV URL
//
const URL = process.env.API || "http://localhost:8001";

async function moderateAll() {
   const browser = await puppeteer.launch({headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox']});
   try {
      console.log("Moderating all");
      const page = await browser.newPage();

      async function followURL(url) {
         const page = await browser.newPage();
         await page.goto(url);
      }

      // first login
      await page.goto(URL+"/login");
      await page.type("#username", "moderator");
      await page.type("#password", "916027bd3a6e3d7131f98d9997db1931a146c2b97f2eb7de75b9bbfb9ed91fb432742e7aea628eafb5ad56027132f7b71fa0");
      await Promise.all([page.click("#submit"), page.waitForNavigation()]);

      console.log("Login successful");

      // then browse to the correct page to view all posts
      await page.goto(URL+"/moderate");
      console.log("went to moderation page");
      
      // now fetch all urls
      const hrefs = await page.$$eval("a", as => as.map(a => a.href))
      
      console.log("hrefs", hrefs);
      // create seperate pages for them
      await Promise.all(hrefs.map(followURL));

      await browser.close();
   } catch (e) {
      console.error(e)
      console.log("Moderating failed...")
      await browser.close();
   }
}

setInterval(() => moderateAll(), 5000);
//moderateAll();
