import { LocalStorage, Route, Server } from '../../../class';

export default class Root extends Route {
  constructor(server: Server) {
    super(server);
    this.conf = {
      path: '/',
    };
  }

  public bind() {
    this.router.get('/m/:id', async (req, res) => {
      try {
        const id = req.params.id.split('.')[0];
        const file = await this.server.client.db.File.findOne({ identifier: id });
        if (!file) return res.status(404).json({ code: this.constants.codes.NOT_FOUND, message: this.constants.messages.NOT_FOUND });
        if (file.downloaded >= file.maxDownloads) return res.status(404).json({ code: this.constants.codes.NOT_FOUND, message: this.constants.messages.NOT_FOUND });
        if (req.query.d === '1') {
          res.contentType('text/html');
          const decomp = await LocalStorage.decompress(file.data);
          res.status(200).send(decomp);
        } else {
          res.contentType(file.mimeType);
          res.status(200).send(file.data);
        }
        return await file.updateOne({ $inc: { downloaded: 1 } });
      } catch (err) {
        return this.handleError(err, res);
      }
    });
  }
}
