import { Context } from 'koa'
import { Body, Controller, Post, Ctx } from '@gem-mine/routing-controllers'
import Statistics from '../service/statistics'

export type UIComponent = {
  name: string;
  count: number;
}

function validateBody(bodyData: any, context: Context): void {
  if(!bodyData.project_id) {
    context.throw(400, 'missing project_id')
  }
  if(!bodyData.component_name) {
    context.throw(400, 'missing component_name')
  }

  if(!bodyData.component_list) {
    context.throw(400, 'missing component_list')
  }

  if(!(bodyData.component_list instanceof Array)) {
    context.throw(400, 'component_list must be array')
  }

  bodyData.component_list.forEach((componentData: UIComponent) => {
    if(!componentData.name) {
      context.throw(400, 'every item in component_list must have name')
    }
    if(typeof componentData.count !== 'number') {
      context.throw(400, 'every item in component_list must have a count as number')
    }
  })
}

@Controller('/statistics')
export default class {
  @Post('/ui')
  async createOne(
    @Body() bodyData: { project_id: string, component_name: string, component_list: Array<UIComponent> },
    @Ctx() context: Context
  ) {
    validateBody(bodyData, context)
    return Statistics.createOne(bodyData)
  }
}
