/*
 * Copyright (C) 2019 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {Plugin} from '@openstapps/api-plugin';
import * as express from 'express';
import {SCMinimalRequest} from './protocol/request.js';
import {SCMinimalResponse} from './protocol/response.js';

/**
 * The Plugin Class
 *
 * This is where all of your logic should take place
 * TODO: rename the class
 */
export class MinimalPlugin extends Plugin {
  /**
   * Calculates the sum of a list of numbers
   *
   * TODO: remove this function and write your own ones
   * @param numbers the list of numbers
   */
  private static sum(numbers: number[]): number {
    return numbers.reduce((a, b) => a + b);
  }

  /**
   * The method that gets called when its route is being invoked
   *
   * For this example the whole purpose of the plugin is to receive a list of numbers and return the sum of them.
   * TODO: remove the body of the function and replace with your own logic
   * @param request the express request object
   * @param response the express response object
   */
  // tslint:disable-next-line:prefer-function-over-method
  protected async onRouteInvoke(request: express.Request, response: express.Response): Promise<void> {
    // get the body from the request as a SCMinimalRequest for static type-safety
    const requestBody = request.body as SCMinimalRequest;

    // create out response body
    const responseBody: SCMinimalResponse = {
      sum: MinimalPlugin.sum(requestBody.numbers),
    };

    // send the response
    response.json(responseBody);
  }
}
