# coding=utf-8
import os
import random

def questionnaireCorrection(result, browser):
  """
  Questionnare correction use case performance test

  Time when:

  1/ "Click answer set" which has already 20 corrections.
  2/ "Fast Input" and display the fast imput form.
  3/ "Add Correction Line to Answer" to create a Correction.
  """
  # - go to the cloudia home page
  browser.open()

  # - login to cloudia
  browser.mainForm.submitLogin(sleep=(1, 2))
  _debug(step='login', content=browser.contents)

  answer_set_url = browser.url + '/answer_set_module/'

  browser.mainForm.submitSelectFavourite(label="Answer Sets to Submit")
  _debug(step='answer_sets', content=browser.contents)

  answer_url = answer_set_url + '50' # XXX: hard coded

  # Time 1/ "Click answer set" which has already 20 corrections.
  result('Click answer set (20 corrections)',
          browser.open(answer_url, sleep=(1,2)))
  _debug(step='answer', content=browser.contents)

  answer_one_url = answer_url + '/1'

  # - open an answer line
  browser.open(answer_one_url)
  _debug(step='answer_one', content=browser.contents)

  fast_input_link = browser.getFastInputLink()

  # Time 2/ "Fast Input" and display the fast imput form.
  result('Fast Input', fast_input_link.click(sleep=(1, 2)))


  # add into /answer_set/module/1 .. 50/1
  # Time 3 "Add Crrection Line to Answer" to create a Correction.
  random_answer_id = random.randrange(1, 50)
  random_answer_one_url = answer_set_url + '%s/1' % random_answer_id
  browser.open(random_answer_one_url)
  fast_input_link = browser.getFastInputLink()
  fast_input_link.click(sleep=(1, 2))
  _printMessage('correction in %s' % random_answer_one_url)
  correction = dict(title='x is missing',
                    description='x is b',
                    comment='because x is q')
  result('Add Correction Line to Answer',
         _addCorrectionLine(browser, **correction))


def _addCorrectionLine(browser,
                       title=None,
                       description=None,
                       comment=None):
  _printMessage("[correction] %s / %s / %s " % (title, description, comment))
  name_temp = "field_editable_listbox_%s_new_001"
  mainForm = browser.mainForm
  mainForm.getControl(name=name_temp % 'source_title').value = title
  mainForm.getControl(name=name_temp % 'source_description').value = description
  mainForm.getControl(name=name_temp % 'comment').value = comment
  return mainForm.submitDialogConfirm(sleep=(5,10))

def _printMessage(msg):
  pid = os.getpid()
  print "\033[0;31m" + str(pid) + "\033[0m: " + str(msg)

def _debug(step='debug1', content=None):
  d = open('/tmp/%s' % step, 'w')
  d.write(str(content))
  d.close()

def _fillForm(browser, kw):
  for k, v in kw.items():
    if k.startswith('subfield') or k.startswith('field') \
         or k.startswith('default_field'):
      browser.mainForm.getControl(name=k).value = v
    else:
      browser.mainForm.getControl(name='field_your_%s' % k).value = v
