<commit_before>express = require 'express'
models  = require '../../../models'
authMiddleware = require '../authentication_middleware'

newFrame = (request) ->
  Frame = request.app.get('models').Frame
  Frame.create (data)

validateNewFrame = (request, response, next) ->
  if request.body["Player1Id"] == request.body["Player2Id"]
    response.status(400).json(error: "Player cannot play against self")
    response.end()
  else if request.body["WinnerId"]
    response.status(400).json(error: "Cannot set winner before shots have been played")
    response.end()
  else
    validatePlayersBelongToLeague request, response, () ->
      validatePlayersDontHaveUnfinishedFrames request, response, next

validatePlayersDontHaveUnfinishedFrames = (request, response, next) ->
  playersIds = [request.body["Player1Id"], request.body["Player2Id"]]
  models.Frame.count(
    where:
      WinnerId: null
      $or: [
        { Player1Id: { $in: playersIds } },
        { Player2Id: { $in: playersIds } }
      ]
  ).then (count) ->
    if count != 0
      response.status(400).json(error: "Players cannot have incomplete frames when creating a new frame")
      response.end()
    else
      next()

validatePlayersBelongToLeague = (request, response, next) ->
  models.Player.count(
      where:
        id: {$in: [request.body["Player1Id"], request.body["Player2Id"]]}
        LeagueId: request.body["LeagueId"]
    ).then (count) ->
      if count != 2
        response.status(400).json(error: "Player(s) do not belong to the given League")
        response.end()
      else
        next()

validateLeaguePrivileges = (request, response, next) ->
  next() # TODO: Check if the user is in the league

module.exports = ->
  router = express.Router()

  router.get '/frames', (request, response) ->
    models.Frame.all().then (frames) ->
      response.json(frames)

  router.post '/frames', validateLeaguePrivileges, validateNewFrame, (request, response) ->
    models.Frame.create(request.body).then (frame) ->
      data =
        event: "frameStart"
        frame: frame.toJSON()
      request.app.get('redisClient').publish(frame.LeagueId, JSON.stringify(data))
      response.status(201).json(frame)

  router.all '/frames/:id/:op?', validateLeaguePrivileges
  router.all '/frames/:id/:op?', (request, response, next) ->
    models.Frame.findOne(
      where: {id: request.params.id},
      include: [
        { model: models.Player, as: 'Player1' },
        { model: models.Player, as: 'Player2' },
        { model: models.League },
        { model: models.Player, as: 'Winner' },
        { model: models.Shot }
      ]
    ).then((frame) ->
      request.frame = frame
      next()
    ).catch( ->
      response.status(400).json(error: 'cannot find user ' + request.params.id)
      response.end()
    )

  router.get '/frames/:id', (request, response) ->
    response.json(request.frame)

  router.delete '/frames/:id', (request, response) ->
    if request.frame.WinnerId
      response.status(400).json(error: "Deleting completed frames is not allowed.")
    else
      request.frame.destroy()
      data =
        event: "frameDelete"
        frame: request.frame.toJSON()
      request.app.get('redisClient').publish(request.frame.LeagueId, JSON.stringify(data))
      response.status(204)

  router.patch '/frames/:id', (request, response) ->
    if request.frame.WinnerId
      response.status(400).json(error: "Changing the winner is not allowed.")
    else
      winnerId = request.body["WinnerId"]
      if winnerId in [request.frame.Player1Id, request.frame.Player2Id]
        request.frame.set('WinnerId', winnerId)
        request.frame.set('endedAt', new Date())
        request.frame.save()
        data =
          event: "frameEnd"
          frame: request.frame.toJSON()
        request.app.get('redisClient').publish(request.frame.LeagueId, JSON.stringify(data))
        response.status(200).json(request.frame)
      else
        response.status(400).json(error: "WinnerId is not a player in this frame")
  router<commit_msg>Actually return response when deleting frame<commit_after>express = require 'express'
models  = require '../../../models'
authMiddleware = require '../authentication_middleware'

newFrame = (request) ->
  Frame = request.app.get('models').Frame
  Frame.create (data)

validateNewFrame = (request, response, next) ->
  if request.body["Player1Id"] == request.body["Player2Id"]
    response.status(400).json(error: "Player cannot play against self")
    response.end()
  else if request.body["WinnerId"]
    response.status(400).json(error: "Cannot set winner before shots have been played")
    response.end()
  else
    validatePlayersBelongToLeague request, response, () ->
      validatePlayersDontHaveUnfinishedFrames request, response, next

validatePlayersDontHaveUnfinishedFrames = (request, response, next) ->
  playersIds = [request.body["Player1Id"], request.body["Player2Id"]]
  models.Frame.count(
    where:
      WinnerId: null
      $or: [
        { Player1Id: { $in: playersIds } },
        { Player2Id: { $in: playersIds } }
      ]
  ).then (count) ->
    if count != 0
      response.status(400).json(error: "Players cannot have incomplete frames when creating a new frame")
      response.end()
    else
      next()

validatePlayersBelongToLeague = (request, response, next) ->
  models.Player.count(
      where:
        id: {$in: [request.body["Player1Id"], request.body["Player2Id"]]}
        LeagueId: request.body["LeagueId"]
    ).then (count) ->
      if count != 2
        response.status(400).json(error: "Player(s) do not belong to the given League")
        response.end()
      else
        next()

validateLeaguePrivileges = (request, response, next) ->
  next() # TODO: Check if the user is in the league

module.exports = ->
  router = express.Router()

  router.get '/frames', (request, response) ->
    models.Frame.all().then (frames) ->
      response.json(frames)

  router.post '/frames', validateLeaguePrivileges, validateNewFrame, (request, response) ->
    models.Frame.create(request.body).then (frame) ->
      data =
        event: "frameStart"
        frame: frame.toJSON()
      request.app.get('redisClient').publish(frame.LeagueId, JSON.stringify(data))
      response.status(201).json(frame)

  router.all '/frames/:id/:op?', validateLeaguePrivileges
  router.all '/frames/:id/:op?', (request, response, next) ->
    models.Frame.findOne(
      where: {id: request.params.id},
      include: [
        { model: models.Player, as: 'Player1' },
        { model: models.Player, as: 'Player2' },
        { model: models.League },
        { model: models.Player, as: 'Winner' },
        { model: models.Shot }
      ]
    ).then((frame) ->
      request.frame = frame
      next()
    ).catch( ->
      response.status(400).json(error: 'cannot find user ' + request.params.id)
      response.end()
    )

  router.get '/frames/:id', (request, response) ->
    response.json(request.frame)

  router.delete '/frames/:id', (request, response) ->
    if request.frame.WinnerId
      response.status(400).json(error: "Deleting completed frames is not allowed.")
    else
      request.frame.destroy()
      data =
        event: "frameDelete"
        frame: request.frame.toJSON()
      request.app.get('redisClient').publish(request.frame.LeagueId, JSON.stringify(data))
      response.status(204).json("")

  router.patch '/frames/:id', (request, response) ->
    if request.frame.WinnerId
      response.status(400).json(error: "Changing the winner is not allowed.")
    else
      winnerId = request.body["WinnerId"]
      if winnerId in [request.frame.Player1Id, request.frame.Player2Id]
        request.frame.set('WinnerId', winnerId)
        request.frame.set('endedAt', new Date())
        request.frame.save()
        data =
          event: "frameEnd"
          frame: request.frame.toJSON()
        request.app.get('redisClient').publish(request.frame.LeagueId, JSON.stringify(data))
        response.status(200).json(request.frame)
      else
        response.status(400).json(error: "WinnerId is not a player in this frame")
  router
{'fraction_non_alphanumeric': 0.14512165151142786, 'fraction_numerical': 0.0115507495699189, 'mean_word_length': 2.9995085995085997, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '667416', 'n_tokens_mistral': 2509, 'n_tokens_neox': 2432, 'n_words': 552}