<commit_before>package controllers

import db.scalikejdbc.RoundJdbc.RoundStatRow
import db.scalikejdbc._
import db.scalikejdbc.rewrite.ImageDbNew.{Limit, SelectionQuery}
import org.intracer.wmua._
import org.intracer.wmua.cmd.SetCurrentRound
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.Controller
import play.api.Play.current
import play.api.i18n.Messages.Implicits._
import play.api.data.validation.{Constraint, Invalid, Valid, ValidationError}
import scalikejdbc._

import scala.util.Try

object Rounds extends Controller with Secured {

  def rounds(contestIdParam: Option[Long] = None) = withAuth({
    user =>
      implicit request =>
        val roundsView = for (contestId <- user.currentContest.orElse(contestIdParam);
                              contest <- ContestJuryJdbc.byId(contestId)) yield {
          val rounds = RoundJdbc.findByContest(contestId)
          val currentRound = rounds.find(_.id == contest.currentRound)

          val roundsStat = ImageJdbc.roundsStat(contestId).groupBy(_._1).map {
            case (rId, s) =>
              val rateMap = s.map {
                case (_, rate, count) => rate -> count
              }.toMap
              rId -> new RateDistribution(rateMap)
          }

          Ok(views.html.rounds(user, rounds, roundsStat,
            editRoundForm, imagesForm.fill(contest.images),
            selectRoundForm.fill(contest.currentRound.map(_.toString)),
            currentRound, contest)
          )
        }
        roundsView.getOrElse(Redirect(routes.Login.index())) // TODO message
  }, User.ADMIN_ROLES)

  def editRound(roundId: Option[Long], contestId: Long) = withAuth({
    user =>
      implicit request =>
        val number = RoundJdbc.findByContest(contestId).size + 1
        val round = roundId.flatMap(RoundJdbc.find).getOrElse(
          new Round(id = None, contest = contestId, number = number)
        )

        val rounds = RoundJdbc.findByContest(contestId)

        val regions = Contests.regions(contestId)

        val jurors = round.id.fold(loadJurors(contestId))(UserJdbc.findByRoundSelection)

        val editRound = EditRound(round, jurors.flatMap(_.id), None)

        val filledRound = editRoundForm.fill(editRound)

        val stat = round.id.map(id => getRoundStat(id, round))

        Ok(views.html.editRound(user, filledRound, round.id.isEmpty, rounds, Some(round.contest), jurors, regions, stat))
  }, User.ADMIN_ROLES)

  def loadJurors(contestId: Long): Seq[User] = {
    UserJdbc.findAllBy(sqls.in(UserJdbc.u.roles, Seq("jury")).and.eq(UserJdbc.u.contest, contestId))
  }

  def loadJurors(contestId: Long, jurorIds: Seq[Long]): Seq[User] = {
    UserJdbc.findAllBy(
      sqls
        .in(UserJdbc.u.id, jurorIds).and
        .in(UserJdbc.u.roles, Seq("jury")).and
        .eq(UserJdbc.u.contest, contestId)
    )
  }

  def saveRound() = withAuth({
    user =>
      implicit request =>

        editRoundForm.bindFromRequest.fold(
          formWithErrors => {
            // binding failure, you retrieve the form containing errors,
            val contestId: Option[Long] = formWithErrors.data.get("contest").map(_.toLong)
            val rounds = contestId.map(RoundJdbc.findByContest).getOrElse(Seq.empty)
            val jurors = loadJurors(contestId.get)
            val roundId = formWithErrors.data.get("id")

            BadRequest(views.html.editRound(user, formWithErrors, newRound = roundId.isEmpty, rounds, contestId, jurors))
          },
          editForm => {<commit_msg>failed round creation should be still new round<commit_after>package controllers

import db.scalikejdbc.RoundJdbc.RoundStatRow
import db.scalikejdbc._
import db.scalikejdbc.rewrite.ImageDbNew.{Limit, SelectionQuery}
import org.intracer.wmua._
import org.intracer.wmua.cmd.SetCurrentRound
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.Controller
import play.api.Play.current
import play.api.i18n.Messages.Implicits._
import play.api.data.validation.{Constraint, Invalid, Valid, ValidationError}
import scalikejdbc._

import scala.util.Try

object Rounds extends Controller with Secured {

  def rounds(contestIdParam: Option[Long] = None) = withAuth({
    user =>
      implicit request =>
        val roundsView = for (contestId <- user.currentContest.orElse(contestIdParam);
                              contest <- ContestJuryJdbc.byId(contestId)) yield {
          val rounds = RoundJdbc.findByContest(contestId)
          val currentRound = rounds.find(_.id == contest.currentRound)

          val roundsStat = ImageJdbc.roundsStat(contestId).groupBy(_._1).map {
            case (rId, s) =>
              val rateMap = s.map {
                case (_, rate, count) => rate -> count
              }.toMap
              rId -> new RateDistribution(rateMap)
          }

          Ok(views.html.rounds(user, rounds, roundsStat,
            editRoundForm, imagesForm.fill(contest.images),
            selectRoundForm.fill(contest.currentRound.map(_.toString)),
            currentRound, contest)
          )
        }
        roundsView.getOrElse(Redirect(routes.Login.index())) // TODO message
  }, User.ADMIN_ROLES)

  def editRound(roundId: Option[Long], contestId: Long) = withAuth({
    user =>
      implicit request =>
        val number = RoundJdbc.findByContest(contestId).size + 1
        val round = roundId.flatMap(RoundJdbc.find).getOrElse(
          new Round(id = None, contest = contestId, number = number)
        )

        val rounds = RoundJdbc.findByContest(contestId)

        val regions = Contests.regions(contestId)

        val jurors = round.id.fold(loadJurors(contestId))(UserJdbc.findByRoundSelection)

        val editRound = EditRound(round, jurors.flatMap(_.id), None)

        val filledRound = editRoundForm.fill(editRound)

        val stat = round.id.map(id => getRoundStat(id, round))

        Ok(views.html.editRound(user, filledRound, round.id.isEmpty, rounds, Some(round.contest), jurors, regions, stat))
  }, User.ADMIN_ROLES)

  def loadJurors(contestId: Long): Seq[User] = {
    UserJdbc.findAllBy(sqls.in(UserJdbc.u.roles, Seq("jury")).and.eq(UserJdbc.u.contest, contestId))
  }

  def loadJurors(contestId: Long, jurorIds: Seq[Long]): Seq[User] = {
    UserJdbc.findAllBy(
      sqls
        .in(UserJdbc.u.id, jurorIds).and
        .in(UserJdbc.u.roles, Seq("jury")).and
        .eq(UserJdbc.u.contest, contestId)
    )
  }

  def saveRound() = withAuth({
    user =>
      implicit request =>

        editRoundForm.bindFromRequest.fold(
          formWithErrors => {
            // binding failure, you retrieve the form containing errors,
            val contestId: Option[Long] = formWithErrors.data.get("contest").map(_.toLong)
            val rounds = contestId.map(RoundJdbc.findByContest).getOrElse(Seq.empty)
            val jurors = loadJurors(contestId.get)
            val hasRoundId = formWithErrors.data.get("id").exists(_.nonEmpty)

            BadRequest(views.html.editRound(user, formWithErrors, newRound = !hasRoundId, rounds, contestId, jurors))
          },
          editForm => {
{'fraction_non_alphanumeric': 0.11486486486486487, 'fraction_numerical': 0.0011261261261261261, 'mean_word_length': 2.8137412775093935, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 29, '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': '1754244', 'n_tokens_mistral': 2275, 'n_tokens_neox': 2190, 'n_words': 413}