from __future__ import print_function
import argparse
from time import gmtime, strftime, time, sleep
from erp5.util import taskdistribution
from erp5.util.testsuite import format_command


class DummyTestResult:

  class DummyTestResultLine:

    def stop(self, duration, stdout='', **kw):
      print('stop: %s' % (kw,))
      print('\n' + stdout)
      print('Ran in %.3fs' % duration)

  done = 0

  def __init__(self, test_name_list):
    print("init: Tests to run: %s" % (','.join(test_name_list)))
    self.test_name_list = test_name_list

  def start(self):
    test_result_line = self.DummyTestResultLine()
    try:
      test_result_line.name = self.test_name_list[self.done]
    except IndexError:
      return
    self.done += 1
    print("start: %s" % (test_result_line.name,))
    return test_result_line

test_list = ['dummy']


def main():
  parser = argparse.ArgumentParser(description='Run a test suite.')
  parser.add_argument('--test_suite', help='The test suite name')
  parser.add_argument('--test_suite_title', help='The test suite title')
  parser.add_argument('--test_node_title', help='The test node title')
  parser.add_argument('--project_title', help='The project title')
  parser.add_argument('--revision', help='The revision to test',
                      default='dummy_revision')
  parser.add_argument('--node_quantity', type=int,
                      help='Number of CPUs to use for the VM')
  parser.add_argument('--master_url',
                      help='The Url of Master controlling test suites')

  args = parser.parse_args()

  test_title = args.test_suite_title or args.test_suite
  if args.master_url:
    tool = taskdistribution.TaskDistributionTool(args.master_url)
    test_result = tool.createTestResult(args.revision,
                                        test_list,
                                        args.test_node_title,
                                        test_title=test_title,
                                        project_title=args.project_title)
    if test_result is None:
      return
  else:
    test_result = DummyTestResult(test_list)

  while 1:
    test_result_line = test_result.start()
    if not test_result_line:
      break
    test = test_result_line.name
    cmd = ['parsed', 'in-vm-test', 'output', test]
    status_dict = {'command': format_command(*cmd)}

    status_dict['stderr'] = 'Standard error'
    status_dict['stdout'] = 'Standard output'

    start = time()
    sleep(2)
    end = time()

    test_result_line.stop(
        date=strftime("%Y/%m/%d %H:%M:%S", gmtime(end)),
        duration=end - start,
        **status_dict)

if __name__ == "__main__":
    main()
