#!/usr/bin/python3
import asyncio
import timer
import signal
import os
import websockets
import conf
import login
from lobby import Lobby
import user
import argparse
import multiprocessing

# default values
Interval = 1
Concurrency = 1000


async def connect(url):
    return await websockets.connect(url)


def on_signal(sig, frame):
    print('received signal:', sig)
    exit(0)


async def timer_callback():
    pass #print('timer')


async def main():
    # signal quit
    signal.signal(signal.SIGINT, on_signal)
    
    t = timer.Timer(1, timer_callback)
    
    # connect to login
    lgn = login.Login(conf.ADDR_LOGIN)
    await lgn.connect()

    u = user.load()
    if not u:
        u = await lgn.register()
        if not u:
            print('register failed')
            return
    else:
        if not await lgn.login(u):
            u = await lgn.register()
            if not u:
                print('login failed and register failed.')
                return

    print('login success: guid=', u.guid)
   
    ## lobby
    print('server addr:', lgn.lobbyAddr)
    server = Lobby(u, lgn.lobbyAddr)
    protocols = [
        #server.C_Login,
        server.C_Heartbeat,
        server.C_ChildrenItemsOf,
        server.C_UserSettings,
        server.C_UpdateBankBalance,
       # server.C_UserBalance,
        server.C_BindAlipay,
        # server.C_PrivateMail,
        # server.C_Activity,
        # server.C_Notice,
        # server.C_Marquee,
    ]

    await server.connect()
    
    # login
    await server.request(server.C_Login)
    await asyncio.sleep(Interval)
    
    while True:
        for protocol in protocols:
            await server.request(protocol)
            await asyncio.sleep(Interval)

    await lgn.close()
    await server.close()

    t.cancel()


def worker(index):
    print('starting ', index, ' process...')
    conf.ClientId = index
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()


if __name__ == '__main__':
    # command line
    parser = argparse.ArgumentParser(description="kingame client")
    #parser.add_argument('-c', '--clientId', required=True, action='store', dest='clientId', metavar='client id', help='setup client id')
    parser.add_argument('-c', '--concurrency', action='store', dest='concurrency', default=1000, type=int, metavar='concurrency', help='set concurrency number')
    parser.add_argument('-i', '--interval', action='store', dest='interval', default=1, type=int, metavar='interval', help='set interval seconds')
    args = parser.parse_args()
    # read parameter
    
    Interval = args.interval
    Concurrency = args.concurrency
    print(Interval, Concurrency)

    print('your parameters: interval=', Interval, ', concurrency=', Concurrency)

    for i in range(Concurrency):
        i += 1
        p = multiprocessing.Process(target=worker, args=(i,))
        p.start()
        #p.join()
        print('Process ', i, ' finished')
    print('All done')
    #worker()

