import asyncio
import json
import utils
import websockets
import user
import traceback


CHANNEL = 'benchmark'
OS = 'robot'
MAKER = 'kingame'
VERSION = 'v0.1'


class Login:
    def __init__(self, addr):
        self._addr = addr
        self._conn = None
        self._lobbyAddr = ''

    @property
    def lobbyAddr(self):
        return self._lobbyAddr

    async def connect(self):
        self._conn = await websockets.connect(self._addr)

    async def close(self):
        await self._conn.close()

    async def register(self):
        try:
            imei = utils.gen_imei()
            ip = utils.gen_ip()
    
            sp = json.dumps({
                "cmd":"reg",
                "params":{
                    "imei" : imei,
                    "channel": CHANNEL,
                    "ip": ip,
                    "os": OS,
                    "maker": MAKER,
                    "version": VERSION,
                },
            })
            await self._conn.send(sp)
            bm = await self._conn.recv()
            obj = json.loads(bm)
    
            if obj['ec'] != 0:
                return False
    
            account = obj['result']['account']
            expire  = obj['result']['expire']
            guid    = obj['result']['guid']
            password= obj['result']['password']
            token   = obj['result']['token']
            self._lobbyAddr     = obj['result']['uri']

            phone = utils.gen_phone()
            u = user.User(guid=guid, account=account, password=password, 
                token=token, expire=expire,imei=imei, 
                ip=ip, phone=phone, uri=self._lobbyAddr)
            #
            user.serialize(u)
            return u
        except Exception as e:
            print('reg', e)
            traceback.print_exc()
            return False

    async def login(self, u):
        try:
            sp = json.dumps({
                "cmd":"login",
                "params":{
                    "account": u.account,
                    "phone": u.phone,
                    "password": u.password,
                    "ip": u.ip,
                    "imei": u.imei,
                },
            })
            await self._conn.send(sp)
            bn = await self._conn.recv()
            #print(bn)
            obj = json.loads(bn)
            ec = obj['ec']
            if ec != 0:
                print('login:', ec)
                return False

            token = obj['result']['token']
            expire = obj['result']['expire']
            uri = obj['result']['uri']
            u.tk.token = token
            u.tk.expire = expire
            u.uri = uri
            self._lobbyAddr = uri

            user.serialize(u)
            return True
        except Exception as e:
            print('login:', e)
            traceback.print_exc()
            return False
