#!/usr/bin/python3
"""
@copyright
(c) Copyright ESO 2019
All Rights Reserved
ESO (eso.org) is an Intergovernmental Organisation, and therefore special legal conditions apply.
@author Cosylab
"""
import sys
import time
import datetime
import argparse
import traceback
import elt.pymal as mal
from elt.error.Exceptions import CiiBaseException

class CiiTestException1(CiiBaseException):
    def __init__(self, arg):
        message = 'This is textual exception: %s'
        super().__init__(message % arg)

class CiiTestException2(CiiBaseException):
    def __init__(self, arg):
        message = 'This is integer exception: %d'
        super().__init__(message % arg)
        self._errorCode = arg

class CiiTestException3(CiiBaseException):
    def __init__(self, arg):
        message = 'This is double exception: %f'
        super().__init__(message % arg)
        self._measurement = arg

class ExceptionThrowTest:
  def __init__(self, exceptions):
      self._exceptions = exceptions

  def run(self):
      print('Starting measurement for number of exceptions: ', self._exceptions)
      start = time.time()
      for i in range(self._exceptions):
          try:
               modulo = i % 3
               if modulo == 1:
                  raise CiiTestException2(i)
               elif modulo == 2:
                  raise CiiTestException3(1.0)
               else:
                  raise CiiTestException1('error')
          except CiiTestException1 as e:
              pass # Do nothing
          except CiiTestException2 as e:
              pass # Do nothing
          except CiiTestException3 as e:
              pass # Do nothing
      end = time.time()
      seconds = end - start
      print('Generating %s exceptions took: %.6f seconds' % (self._exceptions, seconds))
      print('%.6f' % (seconds))

DEFAULT_EXCEPTIONS = 50000

def intGreaterThanZero(arg):
    value = int(arg)
    if value < 1:
        raise argparse.ArgumentTypeError('Error: argument must be greater than zero')
    return value

def _main():
    """Main function implementation."""
    parser = argparse.ArgumentParser(description='Test exception throw duration')
    parser.add_argument('exceptions',
                        type=intGreaterThanZero,
                        help='Positive number of exceptions to generate',
                        nargs='?',
                        default=DEFAULT_EXCEPTIONS)
    args = parser.parse_args()
    ExceptionThrowTest(args.exceptions).run()
    return 0

def main():
    """Wrap main function with exception handler."""
    status = 0
    try:
        status = _main()
    except Exception as e:
         print('FAIL: %s: EXC: %s' % (sys.argv[0], e), file=sys.stderr)
         traceback.print_exc()
         status = 5
    return status

if __name__ == '__main__':
    sys.exit(main())
