import { Request, Response, NextFunction } from 'express';
import { TranslationsService } from '../services/Translations';
import { writeFileSync } from 'fs';

export class TranslationsController {
  constructor(private readonly translationsService: TranslationsService) {
    this.translationsService = translationsService;
  }

  public async read(_: Request, res: Response, next: NextFunction) {
    try {
      const resp = await this.translationsService.readTranslations();
      res.send(resp);
    } catch (err) {
      next(err);
    }
  }

  public async get(req: Request, res: Response, next: NextFunction) {
    try {
      const resp = await this.translationsService.byName(req.params.name);
      res.send(resp);
    } catch (err) {
      next(
        `Something went wrong. Perhaps ${req.params.name} is not a valid translation file`
      );
    }
  }

  public async update(req: Request, res: Response, next: NextFunction) {
    const file = req.params.name + '.json';
    // grab the file and write to it
    let translations: any = {};

    for (const [key, value] of Object.entries(req.body)) {
      translations[key] = {
        message: value
      };
    }

    writeFileSync('translations/' + file, JSON.stringify(translations));
    const updatedFile = await this.translationsService.byName(
      req.params.name + '.json'
    );
    res.send(updatedFile);
  }
}
