{"size": 1196, "ext": "js", "max_stars_repo_path": "route/client.js", "max_stars_repo_name": "sharemyscreen/dev-service", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "route/client.js", "max_issues_repo_name": "sharemyscreen/dev-service", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "route/client.js", "max_forks_repo_name": "sharemyscreen/dev-service", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.0, "max_line_length": 70, "alphanum_fraction": 0.606187291}
const clientModel = require('sharemyscreen-common').clientModel;
const httpHelper = require('sharemyscreen-http-helper');

function registerRoute (router) {
  router.get('/clients', getClients);

  router.post('/clients', postClient);
}

function getClients (req, res, next) {
  clientModel.getAll(function (err, fClients) {
    if (err) {
      next(err);
    } else {
      fClients.forEach(function (client, i) {
        fClients[i] = client.safePrint();
      });
      httpHelper.sendReply(res, 200, fClients);
    }
  });
}

function postClient (req, res, next) {
  if (req.body.name == null) {
    httpHelper.sendReply(res, httpHelper.error.invalidRequestError());
  } else {
    clientModel.getByName(req.body.name, function (err, fClient) {
      if (err) {
        next(err);
      } else if (fClient != null) {
        httpHelper.sendReply(res, httpHelper.error.clientExist());
      } else {
        clientModel.createNew(req.body.name, function (err, cClient) {
          if (err) {
            next(err);
          } else {
            httpHelper.sendReply(res, 201, cClient.safePrint());
          }
        });
      }
    });
  }
}

module.exports.registerRoute = registerRoute;
