import { fromJS } from 'immutable'

import { PARENT_TYPE_QUIZ } from '@instructure/quiz-common/lib/constants'

import Item from '../../../../../records/Item'
import QuizEntry from '../../../../../records/QuizEntry'
import withContext from '../../../../../../../tests/util/withContext'
import { setFakeStore, unsetFakeStore } from '../../../../../../reduxStore'

import ItemOverride from '../index'

describe('ItemOverride', () => {
  const itemAttributes = {
    id: '1',
    interactionType: '1',
    title: 'Pizza',
    itemBody: 'Pineapple on pizza is:',
    interactionData: {
      choices: [
        { id: 'id1', itemBody: 'an abomination', position: 1 },
        { id: 'id2', itemBody: 'fine, I guess', position: 2 },
        { id: 'id3', itemBody: 'delicious', position: 3 }
      ]
    },
    scoringData: { value: 'id2' }
  }
  const quizEntryAttributes = {
    id: '3',
    entryType: 'BankEntry',
    entry: { id: '2' }
  }
  const itemOverrides = {
    properties: { varyPointsByAnswer: true },
    scoringAlgorithm: 'VaryPointsByAnswer',
    scoringData: {
      values: [
        { value: 'id1', points: 3 },
        { value: 'id2', points: 1 },
        { value: 'id2', points: 0 }
      ]
    }
  }
  const quizId = '1'
  const state = {
    quizzes: { activeQuizId: quizId },
    interactionTypes: {
      1: { id: '1', name: 'Multiple Choice', slug: 'choice' }
    },
    items: {
      1: itemAttributes
    },
    bankEntries: {
      2: { id: '2', entryType: 'Item', entry: { id: '1' } }
    },
    quizEntries: {
      3: quizEntryAttributes
    },
    modifications: {
      quizEntries: { 3: { properties: { itemOverrides } } }
    }
  }

  const item = new Item(fromJS(itemAttributes))
  const quizEntry = new QuizEntry(fromJS(quizEntryAttributes))

  const testbed = createTestbed(withContext(ItemOverride, state), {
    entry: item,
    guid: '1',
    handleQuizEntryPointsChange: () => {},
    parentId: quizId,
    parentType: PARENT_TYPE_QUIZ,
    quizEntry
  })

  beforeEach(() => setFakeStore(fromJS(state)))
  afterEach(() => unsetFakeStore())

  it('passes property overrides through to the interaction component', () => {
    testbed.render()
    const labels = testbed.findChildrenByTagName('label')
    const varyPointsLabel = labels.find(label => label.innerText.includes('Vary points by answer'))
    const varyPointsCheckbox = document.getElementById(varyPointsLabel.htmlFor)
    expect(varyPointsCheckbox.checked).to.be.true()
  })

  it('passes scoringData overrides through to the interaction component', () => {
    testbed.render()
    const numberInputs = testbed.findChildrenByTagNameAndAttribute('input', 'inputmode', 'numeric')
    expect(numberInputs.map(input => input.value)).to.deep.equal(
      itemOverrides.scoringData.values.map(override => override.points.toString())
    )
  })
})
