from pyda.api.md_constant import (
    DAF_TYPE_Future,
    DAF_TYPE_Stock,
    DAF_SUB_Append,
    DAF_SUB_Unsubcribe,
)

from market_demo import MyMarketApi


def show_market_help():
    """显示行情接口帮助信息"""
    print("\n------ 测试行情接口 ------")
    print("  Y 连接并登录期货行情账号")
    print("  N 连接并登录股票行情账号")
    print("  B 订阅行情")
    print("  C 退订行情")
    print("  D 订阅股票经济商")
    print("  ? 帮助")
    print("  * 返回上级")
    print("--------------------------")
    print("请输入命令:")


def login_check(api, help_text):
    """检查API是否创建并登录"""
    if api and api.login_status:
        print(help_text)
        return True
    else:
        print("请先输入命令 'Y'或者'N' 连接并登陆")
        return False


def test_market():
    """测试行情接口"""
    show_market_help()

    heartbeat = 60

    future_userid = "AF20248889"
    future_password = "888888"
    future_address = "175.45.34.88:9795"

    future_codes = ["CL2501"]
    future_req = {
        "MarketType": DAF_TYPE_Future,
        "SubscMode": DAF_SUB_Append,
        "ExchangeCode": "CME",
        "MarketTrcode": future_codes
    }
    future_contcode = "GC1903"

    stock_userid = "AS20248889"
    stock_password = "888889"
    stock_address = "222.73.105.170:9440"

    stock_codes = ["00001.HK", "00002.HK"]
    stock_req = {
        "MarketType": DAF_TYPE_Stock,
        "SubscMode": DAF_SUB_Append,
        "ExchangeCode": "HKEX",
        "MarketTrcode": stock_codes
    }
    stock_contcode = "00700.HK"

    api = None

    while True:
        cmd = input().strip().upper()

        if cmd == "*":
            print("返回上一级....")
            break

        elif cmd == "?":
            show_market_help()

        elif cmd in ["Y", "N"]:
            print("连接并登录...")

            if cmd == "Y":
                address = future_address
                userid = future_userid
                password = future_password

                sub_req = future_req
                contcode = future_contcode
            else:
                address = stock_address
                userid = stock_userid
                password = stock_password

                sub_req = stock_req
                contcode = stock_contcode
            api = MyMarketApi(userid, password)
            api.createMarketApi(True, "da", cmd)
            api.registerNameServer("tcp://" + address)
            api.setHeartBeatTimeout(heartbeat)
            api.init()

        elif cmd == "B":
            if login_check(api, "订阅行情"):
                api.reqid += 1
                n: int = api.reqMarketData(sub_req, api.reqid)
                if n:
                    print(f"订阅行情请求发送失败，错误码{n}")
                else:
                    print("订阅行情请求发送成功")

        elif cmd == "C":
            if login_check(api, "退订行情"):
                api.reqid += 1
                unsub_req = sub_req.copy()
                unsub_req["MarketTrcode"] = sub_req["MarketTrcode"][:1]
                unsub_req["SubscMode"] = DAF_SUB_Unsubcribe
                n: int = api.reqMarketData(unsub_req, api.reqid)
                if n:
                    print(f"退订行情请求发送失败，错误码{n}")
                else:
                    print("退订行情请求发送成功")

        elif cmd == "D":
            if login_check(api, "订阅经济商"):
                api.reqid += 1
                req: dict = {"ContCode": contcode}
                res: bool = api.reqBrokerData(req, api.reqid)
                if not res:
                    print("订阅经济商请求发送失败")
                else:
                    print("订阅经济商请求发送成功")

        else:
            print("不能识别的命令!")

    if api:
        api.exit()


def show_root_help():
    print("\n※※※※※※※  直达接口测试程序  ※※※※※※※")
    print("\n  M 测试行情功能....")
    print("  X 退出测试程序")
    print("  ? 帮助")
    print("------------------------------------------")
    print("请输入命令:")

def main():
    show_root_help()

    while True:
        cmd = input().strip().upper()
        if cmd == "X":
            break
        elif cmd == "*":
            show_root_help()
        elif cmd == "?":
            show_root_help()
        elif cmd == "M":
            test_market()
            show_root_help()
        else:
            print("不能识别的命令!")

    print("安全退出程序.")

if __name__ == "__main__":
    main()
