const bodyParser = require('body-parser');
const pathExists = require('path-exists');
const fs = require('fs')
const genericFunctions = require('../functions/generic')
const path = require("path");

var myArgs = process.argv.slice(2);
var userDetails = JSON.parse(fs.readFileSync(path.resolve(__dirname, "../data/userDetails.json")));

var express = require('express');
var router = express.Router();
router.use(bodyParser.urlencoded({
  extended: true
}));

/* GET users listing. */
async function buildPage() {
  router.post('/', async (req, res) => {
  const pExists = pathExists.sync(req.body.path)
  const i = req.body.url
  const test = i.lastIndexOf('/')
  const id = i.substring(test + 1)

  if (i.includes("/album/")) {
    sid = `spotify:album:${id}`
  } else if (i.includes("/playlist/")) {
    sid = `spotify:playlist:${id}`
  } else {
    console.log('failed')
  }

  if (pExists === true) {
    let isMounted = await genericFunctions.mount(req.body.path, userDetails.path)
    // console.log(isMounted)
    if (isMounted === true) {
    try {
      fs.writeFileSync(`${userDetails.path}/diskplayer.contents`, sid)
      res.render('success', {
        path: req.body.path,
        url: req.body.url
      })
      await genericFunctions.unMount(userDetails.path)
    } catch (err) {
      res.render('failed', {
        error: err
      })
      await genericFunctions.unMount(userDetails.path)
    }
  } else {
    res.render('failed', {
      error: 'Path does not exist'
    })
} 
}
})
};


buildPage()
module.exports = router;
