import express from 'express';

const app = express()
const lst = [];  // List of (name, complete time) for all items ever added.

// Returns a textual description of all items either uncompleted or completed
// within the last 5 seconds.
app.get('/list', (req, res) => {
    const since = Date.now() - 5000;
    const text = lst.filter(t => t[1] < 0 || since <= t[1])
        .map(t => (0 <= t[1]) ? t[0] + "\t(completed)" : t[0])
        .join('\n')
    res.type('text/plain');
    res.send(text);
  });

// Adds the given item to the list or, if it is already completed, changes it
// back to non-completed.
app.post('/add', (req, res) => {
    const name = req.query.name;
    if (name) {
      const names = lst.map(t => t[0]);
      const index = names.indexOf(name);
      if (index < 0) {
        lst.push([name, -1]);
        res.send("added");
      } else if (lst[index][1] >= 0) {
        lst[index][1] = -1;
        res.send("added");
      } else {
        res.send("added already");
      }
    }
  });

// Marks the given item as having just been completed.
app.post('/completed', (req, res) => {
    const name = req.query.name;
    if (name) {
      const names = lst.map(t => t[0]);
      const index = names.indexOf(name);
      if (index >= 0) {
        lst[index][1] = Date.now();
        res.send("completed");
      }
    }
  });

app.listen(4567, () => console.log('App is running...'))