# coding=utf-8
import os

def qa(**kw):
  return dict(kw)

# Question and Answer
# Put questions here is because it is convenient for debugging.
# Only "answer and field_format" are essential in this performance test.
qa_data_list = [
  qa(question="What is the nature of the organisation?",
     answer="not-for-profit",
     field_format="selection_answer"),
  qa(question="Is the entity for which the ERP is to be implemented  itself a subsidiary, branch or departement of a larger organisation?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="What is the name of the organisation or group to which this entity belongs ?",
     answer="Foo",
     field_format="string_answer"),
  qa(question="What is the main country of the organisation or group to which this entity belongs?",
     answer="Japan",
     field_format="string_answer"),
  qa(question="How many employees or permanent staff does the organisation or group to which this entity belongs have?",
     answer="10000",
     field_format="integer_answer"),
  qa(question="What is the number of people working only occasionally for the organisation or group to which this entity belongs?",
     answer="100",
     field_format="integer_answer"),
  qa(question="How many offices, stores or factories does the organisation or group to which this entity belongs have?",
     answer="5",
     field_format="integer_answer"),
  # How do I predict this?
  qa(question="some questions skipped. Question The following questions are about the entity (eg. subsidiary, branch or department), for which the ERP should be implemented. We will refer to it as the 'organisation' or the 'implementation field'.",
     answer="",
     field_format="skip_answer"),
  qa(question="What is the name of the implementation field, e.g. the entity for which the ERP is to be implemented?",
     answer="erp",
     field_format="string_answer"),
  qa(question="What is the country of the implementation field?",
     answer="japan",
     field_format="string_answer"),
  qa(question="How many employees or permanent staff are working for the implementation field?",
     answer="30",
     field_format="integer_answer"),
  qa(question="What is the number of people working only occasionally for the implementation field?",
     answer="20",
     field_format="integer_answer"),
  qa(question="How many offices, stores or factories does the implementation field have?",
     answer="2",
     field_format="integer_answer"),
  qa(question="What does the implementation field sell, offer or produce?",
     answer="sell",
     field_format="text_answer"),
  qa(question="What does the implementation field purchase, recycle, receives or uses?",
     answer="recycle",
     field_format="text_answer"),
  qa(question="Who are the contacts of the implementation field? ",
     answer="me",
     field_format="text_answer"),
  qa(question="What are the typical skills and initial training of the staff?",
     answer="IT",
     field_format="text_answer"),
  qa(question="Please provide an example of management area or of business process which the organisation is handling in a way which it considers itself as being good or successful. Explain what reasons make his business process or business area successful.",
     answer="x",
     field_format="text_answer"),
  qa(question="Please provide an example of management area or of business process which the organisation is handling in a way which it considers itself as being poor or wrong, and which could be improved. Explain from what point of view the management area or business process is currently not well implemented.",
     answer="x",
     field_format="text_answer"),
   # again skip..
  qa(question="Question Now we are going to ask you three improvements (each one in a separate question) that you expect from an ERP for your business. These improvements might be or might be not related to the previous question about the bad business process. Please first write about the improvement with the highest priority. This should usually be the improvement which would lead to the highest return of investment for your company.",
     answer="",
     field_format="skip_answer"),
 qa(question="Explain what the organisation expects from an ERP as 1st priority to improve its own management?",
     answer="x",
     field_format="text_answer"),
  qa(question="Please explain why the 1st expectation will improve your business.",
     answer="x",
     field_format="text_answer"),
  qa(question="Explain what the organisation expects from an ERP as 2nd priority to improve its own management?",
     answer="x",
     field_format="text_answer"),
  qa(question="Please explain why the 2nd expectation will improve your business.",
     answer="x",
     field_format="text_answer"),
  qa(question="Explain what the organisation expects from an ERP as 3rd priority to improve its own management?",
     answer="x",
     field_format="text_answer"),
  qa(question="Please explain why the 3rd expectation will improve your business.",
     answer="x",
     field_format="text_answer"),
  qa(question="What is the social form of the organisation?",
     answer="mail",
     field_format="string_answer"),
  qa(question="Do your contacts require you to print labels with specific infield_formation on the parcels you are shipping?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="Are all your employees working at the same building?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="Is your company an e-commerce company or a company which sells products through a web site?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Is it OK, if all employees have access to all documents?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Is it absolutely required to have all your data on your own server - even if it would drastically increase the cost and effort of your ERP implementation?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="Do you need to access your ERP system outside of your compoany's sites?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="How many people will use the ERP?",
     answer="20",
     field_format="integer_answer"),
  qa(question="Please describe who will use the ERP.",
     answer="every body use it.",
     field_format="text_answer"),
  qa(question="Will there be more than one sales agent using the ERP?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="Should one sales agent be able to see the infield_formation of another sales agent?",
     answer="yes",
     field_format="selection_answer"),
  qa(question="Does your company ship products to clients?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="Whenever you package products before shipping them to a customer, can the customer customize the packaging? In other words, can the customer define how they want the package to be made?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="How does the picking process work at the shipment warehouse?",
     answer="per_customer",
     field_format="selection_answer"),
  qa(question="Does your company have to handle returned goods?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="What kind of clients does the company have?",
     answer="consumer",
     field_format="multiselection_answer"),
  qa(question="Do you have profit / and loss analysis per division or business unit in your comany?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="Do you have reliable internet connections at all of your company's sites that need access to the ERP system?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="Does the entity for which the ERP is to be implemented have any subsidiaries itself?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="Do you need budget accounting?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="What are the dimensions of your budget?",
     answer="It is 100.",
     field_format="text_answer"),
  qa(question="Whenever you received a parcel with goods you purchased, does your company have a formal quality assurance step where you inspect goods in detail or even test them before validating the reception of goods or do you simply count goods and make sure they are the same ones as those which were ordered?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="Does your organisation have any retail store?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="Who has acces to commercial accounting?",
     answer="accontants are.",
     field_format="text_answer"),
  qa(question="Do you have a distribution channel based on resellers?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do you sometimes issue press campaigns?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="Do you have to contact many journalists, media or other opinion-makers ?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Is your process to hire new staff formalized with defined steps and reports about hiring meetings, assessments questionnaires and tests?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="Please explain, how your process to hire new staff is formalized. Explain steps in the process, like hiring meetings, assessments, questionnaires and tests as well as the used reports.",
     answer="meetings then inteview.",
     field_format="text_answer"),
  qa(question="Do you have a contact database of journalists, media  or other opinion-makers?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do you issue press release and contact journalists by yourself ?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do you need to organize conferences or large meetings ?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do you need to keep a documentation about products you sell?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do you need to keep product description or name in multiple languages ?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Is there any product which you sell using different units (ex. kg or l ) ?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do you sell products using the same unit  as the stock keep unit (SKU) or do you sometimes need to sell products using another unit than the SKU ?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do you need to keep accounting of different companies of yours in the same system ?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Are the people who receive payment orders at the same place as those who post accounting transactions?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do people who process payments need a copy of the 'payment request' (e.g. invoice paper) sent by the supplier ?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Is it possible to implement the worklfow of validating payment requests without having a copy of payment request documents such as invoice?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Is it useful to implement the worklfow of validating payment requests by digitizing payments documents even if digitization takes 5 minutes per document?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do you need to keep track of government subisidies in the accounting ?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do you need to keep track of R&D effort for tax reporting purpose ?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="How many people can your company assign for the ERP5 implementation?",
     answer="3",
     field_format="integer_answer"),
  qa(question="Your company is a production company?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do you need to sell the same product under different brands ?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do you need to check the identity of a client before validating a sales order?",
     answer="1",
     field_format="boolean_answer"),
  qa(question="Is it possible to ship goods to a different address or organisation than the one registered for a given client ?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do you have only one supplier for every product or component you purchase ?",
     answer="0",
     field_format="boolean_answer"),
  qa(question="Do you need to compute project cost ?",
     answer="0",
     field_format="boolean_answer"),
  #qa(question="Please fill in and upload the category spreadsheet.",
  #   answer="('aggregate', '/erp5/answer_set_module/2/75')",
  #   field_format=""),
]

def questionnaireFillout(result, browser):
  """
  Questionnare FillOut use case performance test

  Time when:
  1/ "Fill out" on the  questionnaire until the answer set is created
  2/ "Continue" and the first question is displayed
  3/ "Answer Question" and the next question is displayed.
  4/ specifically for the question "Please upload the configuration
     spreadsheet.
     following spreadsheet should be used
     http://www.osoe-project.org/P-OSOE-Configuration.Sample
  """
  # - go to the cloudia home page
  browser.open()

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

  questionare_url = browser.url + '/questionnaire_module/'
  # - open questionare_module
  browser.open(questionare_url)

  lecture_url = questionare_url + '6'
  # - open ERP5 Configuration Lecture
  browser.open(lecture_url, sleep=(1,2))

  _debug(step='questionare', content=browser.contents)

  fill_out_action = lecture_url + "/Questionnaire_createAnswerSet"
  # 1/ "Fill out"
  result('fill out', browser.open(fill_out_action, sleep=(1,2)))
  _debug(step='fillout', content=browser.contents)

  # 2/ "Continue" and First question
  result('first question',  browser.mainForm.submitDialogConfirm(sleep=(3, 8)))
  _debug(step='first_question', content=browser.contents)

  # 3/ "Answer Question" and the next question is displayed.
  first_qa = qa_data_list[0]
  result('first answer', _fillAnswer(browser, first_qa))

  # answering questions before upload
  _answering(browser)

  # 4/ upload
  result('upload', _uploadTest(browser))

def _uploadTest(browser):
  def makeFilePath(name):
    return os.path.join(os.path.dirname(__file__), 'data', name)

  with open(makeFilePath('P-OSOE-Configuration.Sample-003-en.ods'), 'rb') as f:
    ods = f.read()
  import cStringIO
  fctl = browser.mainForm.getControl(name='field_your_file')
  fctl.add_file(cStringIO.StringIO(ods),
               'application/vnd.oasis.opendocument.spreadsheet',
               'P-OSOE-Configuration.Test-001-en.ods')
  return browser.mainForm.submitDialogConfirm(sleep=(3, 10))

def _fillAnswer(browser, qa):
  field_format = qa['field_format']
  answer = qa['answer']
  question = qa['question']
  _printMessage(question)
  list_answer = ("boolean_answer", "selection_answer", "multiselection_answer")
  if field_format in list_answer:
    answer = [answer]
  if field_format != "skip_answer":
    _fillForm(browser, {field_format:answer})
  return browser.mainForm.submitDialogConfirm(sleep=(3, 8))

def _answering(browser):
  for qa in qa_data_list[1:]:
    _fillAnswer(browser, qa)

def _printMessage(msg):
  pid = os.getpid()
  print "\033[0;31m" + str(pid) + "\033[0m: " + 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
