import {GraphQLError} from 'graphql/error'
import {GraphQLList} from 'graphql/type'

import {handleError} from 'src/server/graphql/models/util'
import {getLatestCycleForChapter} from 'src/server/db/cycle'
import {getPlayerById} from 'src/server/db/player'
import {
  getProjectsForChapterInCycle,
  getProjectsForPlayer,
  findProjectsAndReviewResponsesForPlayer,
} from 'src/server/db/project'

import {ProjectWithReviewResponses, ProjectsSummary} from './schema'

export default {
  getProjectSummaryForPlayer: {
    type: ProjectsSummary,
    async resolve(source, args, {rootValue: {currentUser}}) {
      try {
        if (!currentUser) {
          throw new GraphQLError('You are not authorized to do that.')
        }

        const player = await getPlayerById(currentUser.id, {mergeChapter: true})
        const cycle = await getLatestCycleForChapter(player.chapter.id)

        const numActiveProjectsForCycle = await getProjectsForChapterInCycle(player.chapter.id, cycle.id).count()
        const numTotalProjectsForPlayer = await getProjectsForPlayer(player.id).count()

        return {numActiveProjectsForCycle, numTotalProjectsForPlayer}
      } catch (err) {
        handleError(err)
      }
    },
  },
  getProjectsAndReviewResponsesForPlayer: {
    type: new GraphQLList(ProjectWithReviewResponses),
    async resolve(source, args, {rootValue: {currentUser}}) {
      try {
        if (!currentUser) {
          throw new GraphQLError('You are not authorized to do that.')
        }

        const player = await getPlayerById(currentUser.id, {mergeChapter: true})
        const cycle = await getLatestCycleForChapter(player.chapter.id)

        const projects = await findProjectsAndReviewResponsesForPlayer(player.chapter.id, cycle.id, player.id)
        return projects
      } catch (err) {
        handleError(err)
      }
    },
  },
}

@@ -249,16 +249,73 @@
 player'%0A
+import %7BgetModeratorById%7D from 'src/server/db/moderator'%0A
 import %7B
@@ -786,32 +786,42 @@
       const 
-player =
+user = (%0A         
  await getPl
@@ -858,32 +858,116 @@
 eChapter: true%7D)
+ %7C%7C%0A          await getModeratorById(currentUser.id, %7BmergeChapter: true%7D)%0A        )
 %0A        const c
@@ -996,36 +996,34 @@
 CycleForChapter(
-play
+us
 er.chapter.id)%0A%0A
@@ -1099,20 +1099,18 @@
 InCycle(
-play
+us
 er.chapt
@@ -1203,20 +1203,18 @@
 rPlayer(
-play
+us
 er.id).c

allow moderators to issue getProjectSummaryForPlayer