#!/usr/bin/python3

''' init kingame zookeeper
# config items
- games
- channels
- client addrs
- vip
- wallet

# zk path

- /kg/conf/games
- /kg/conf/channels
- /kg/conf/client_addrs
- /kg/conf/vip
- /kg/conf/wallet

'''
import json
import argparse
from kazoo.client import KazooClient
from kazoo.client import KazooState
from kazoo.client import KeeperState
from kazoo.security import make_digest_acl
from conf import *


g_map_path_value = {
    "/kg/conf/wallet": json_wallet,
    "/kg/conf/games": json_games,
    "/kg/conf/channels": json_channels,
    "/kg/conf/clientaddrs": json_client_addrs,
    "/kg/conf/vip": json_vip,
    "/kg/conf/servers/redis": json_redis,
    "/kg/conf/servers/mq": json_mq,
    "/kg/conf/servers/login": json_login,
}
    

def on_zk_events(state):
    if state == KazooState.LOST:
        print('lost connection')
    elif state == KazooState.SUSPENDED:
        print('suspended')
    elif state == KazooState.CONNECTED:
        print('connected')
    else:
        print('status:', state)


def connect():
    zk = KazooClient(hosts=ZkAuth.addr)
    zk.add_listener(on_zk_events)
    zk.start()
    zk.add_auth('digest', ZkAuth.username + ':' + ZkAuth.password)
    return zk


def import_config():
    zk = connect()
    acl = (make_digest_acl(ZkAuth.username, ZkAuth.password, all=True), )

    # create all paths
    for k, v in g_map_path_value.items():
        zk.ensure_path(k, acl=acl)
        zk.set(k, bytes(v, encoding='utf-8'))
    for leaf in nodes:
        zk.ensure_path('/kg/app/' + leaf, acl=acl)

    zk.stop()


# validate config
def test_config():
    jsons = [json_games, json_channels, json_client_addrs, json_vip, json_wallet, json_login, json_mq, json_redis]
    for t in jsons:
        try:
            json.loads(t)
        except:
            print(t)
            return False
    return True


def main():
    parser = argparse.ArgumentParser(description='zookeeper initializer')
    parser.add_argument('-t', '--test', action='store_true', dest='test', default=False, help='test config')
    args = parser.parse_args()
    if args.test:
        if test_config():
            print('config test pass')
        else:
            print('config test failed')
        return

    # import
    if not test_config():
        print('config error')
        return
    
    import_config()


if __name__ == '__main__':
    main()

""" 使用方式:
首先配置 conf.py

python zk.py -h  查看使用说明
python zk.py -t  测试配置是否正确
python zk.py     执行导入
"""