#!/usr/bin/env python3

import sys
import json
import re
import asyncio
import time
import socket

# for python 3.6
@asyncio.coroutine
def check_connect(hostname,port,l):
    # print('check',hostname,port)
    while True:
        try:
            r, w = yield from asyncio.open_connection(hostname,port,loop=l)
            w.close()
            # print('ready',hostname,port)
            return True
        except socket.herror:
            return False
        except socket.gaierror:
            return False
        except OSError as e:
            # print(e)
            yield from asyncio.sleep(3)

# async def wait_result(l):
#     r = await asyncio.gather(*[check_connect(*x) for x in l])
#     print(r)

def main():
    if len(sys.argv) < 3:
        # print('usage: [script] [json file] [eng|comp]')
        sys.exit(1)
        return
    
    # set target
    if sys.argv[2] == 'eng':
        target = 'HRIEngine'
    elif sys.argv[2] == 'comp':
        target = 'HRIComponent'
    else:
        sys.exit(1)
        return

    # load client_info
    with open(sys.argv[1], 'r') as f:
        d = json.load(f)
    
    # print(d,type(d))

    # extract hostname:port 
    pat = re.compile('http://([^/:]+):(\d+)')
    # get a list of (hostname,port)
    d = [ m.group(1,2) for k, v in d.items() if target in k for m in [pat.search(v['url'])] if m]
    
    loop = asyncio.get_event_loop()
    try:
        r = loop.run_until_complete(asyncio.gather(*[check_connect(*x,loop) for x in d]))
        if not all(r):
            print('Error')
            sys.exit(2)
        # print(r)
    except KeyboardInterrupt:
        print('Interrupted')
    # r = loop.run_until_complete(asyncio.gather(check_connect(*d[0],loop)))
    loop.close()
    # asyncio.run(wait_result())
    print('ready all', target)

if __name__ == '__main__':
    main()