import gql from 'graphql-tag'
import possiblePositions from '@/app/euromat/possiblePositions'

export function getPositionById (id) {
  return possiblePositions.find(option => option.id === id).position
}

export const apolloThesesQuery = gql`{
  allQuestions(orderBy: ROW_ID_ASC) {
    nodes {
      category: categoryByCategoryRowId {
        id
        title
      }
      title
      rowId
      id
    }
  }
}`

export const apolloThesesUpdate = data => data.allQuestions.nodes.map(node => ({
  id: node.rowId,
  thesis: {
    de: node.title
  },
  category: {
    de: node.category ? node.category.title : ''
  }
}))

export const apolloThesesCountQuery = gql`{
  allQuestions {
    totalCount
  }
}`

export const apolloThesesCountUpdate = data => data.allQuestions.totalCount

export const apolloPersonsForResultsQuery = gql`{
  allPeople(condition: {role: KANDIMAT_CANDIDATE}) {
    nodes {
      id
      firstName
      lastName
      rowId
      answers: answersByPersonRowId {
        nodes {
          id
          position
          questionRowId
          text
        }
      }
    }
  }
}`

export const apolloPersonsForResultsUpdate = data => data.allPeople.nodes.map(person => ({
  id: person.rowId,
  name: `${person.firstName} ${person.lastName}`,
  token: person.firstName.charAt(0) + person.lastName.charAt(0),
  positions: person.answers.nodes.map(answer => ({
    thesis: answer.questionRowId,
    position: getPositionById(answer.position),
    statement: {
      de: answer.text
    }
  }))
}))

export const apolloPersonPositionsQuery = gql`
  query Person($partyId: Int!) {
    personByRowId(rowId: $partyId) {
      id
      firstName
      lastName
      answers: answersByPersonRowId {
        nodes {
          id
          position
          personRowId
          text
          question: questionByQuestionRowId {
            id
            rowId
          }
        }
      }
    }
  }`

export const apolloPersonPositionsUpdate = data => {
  const person = data.personByRowId
  return {
    id: person.rowId,
    name: `${person.firstName} ${person.lastName}`,
    token: person.firstName.charAt(0) + person.lastName.charAt(0),
    theses: person.answers ? person.answers.nodes.map(answer => {
      const question = answer.question
      return question ? {
        id: question.rowId,
        position: getPositionById(answer.position),
        statement: answer.text,
        showStatement: false
      } : null
    }) : []
  }
}
