#!/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 elt.pymal as mal
from ModCiiSerializationTest.Elt.Error.IcdTest.CiiSerializationTest import CiiSerializationTestSync
from ModCiiSerializableException.Elt.Error.Icd import CiiSerializableException

NO_EXCEPT_ARG = 'first'
EXCEPT_ARG = 'error'
AMI_TEST_FLAG = '--testAMI'

class MyError(RuntimeError):
    pass

def _main():
    """Main function implementation."""
    uri = 'zpb.rr://127.0.0.1:12081/CiiSerializationTest/inst_1'
    scheme = 'zpb.rr'
    malProperties = {}
    qos = [ mal.rr.qos.ReplyTime(datetime.timedelta(seconds=3)) ]

    # Setup
    malInstance = mal.loadMal('zpb', malProperties)
    ciiFactory = mal.CiiFactory.getInstance()
    ciiFactory.registerMal(scheme, malInstance)

    with ciiFactory.getClient(uri, CiiSerializationTestSync, 
            qos = qos, 
            malSpecificProperties=malProperties) as client:

        if not AMI_TEST_FLAG in sys.argv[1:]:
            try:
                print('- Performing simple test call')
                arg = NO_EXCEPT_ARG
                reply = client.methodWithException(arg)
                if reply != arg:
                    raise MyError('Did not get expeced reply for (%s) from server: %s' %
                                  (arg, reply))
                arg = EXCEPT_ARG 
                print('- Performing call that should raise exception')
                reply = client.methodWithException(arg)
                raise MyError('Client did not receive expected exception')
            except CiiSerializableException as e:
              if arg == EXCEPT_ARG: 
                  print("OK: Got CiiSerializableException: %s" %  (e,))
              else:
                raise
        # Disabled by default, enable by specifiying --testAMI on cmd line
        else:
            print('- Executing ami call, not expecting any exception')
            ami = client.amiMethodWithException(NO_EXCEPT_ARG)
            if ami is None:
                raise RuntimeError('amiMethodWithException did not return ami')
            for item in ami:
                print(item.get())
            ami.close()
            print('OK')
            print('- Executing ami call, exception should be raised')
            ami = client.amiMethodWithException(EXCEPT_ARG)
            if ami is None:
                raise RuntimeError('amiMethodWithException did not return ami')
            try:
                for item in ami:
                    print(item.get())
                raise MyError('ami exceptoion was not raised')
            except MyError:
                raise
            except Exception as e:
                print('OK: ami raised exception: %s' % e)
            finally:
                ami.close()
    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)
         status = 5
    if status == 0:
        print('PASS')
    return status

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