# coding: utf-8
import argparse
import os
import sys
import configparser
# 这几项添加路径，必须放前面，否则后续import会报错
# 获取组名
input_team_name = sys.argv
try:
    team_index = input_team_name.index('-t')
except ValueError:
    raise Exception("组名是必填参数，请设置....")
else:
    TEAM_NAME = input_team_name[team_index+1]
BASIC_PATH = os.path.dirname(os.path.abspath(__file__))
TEAM_PATH = os.path.abspath(os.path.join(BASIC_PATH, '../{}/'.format(TEAM_NAME)))
sys.path.append(TEAM_PATH)
PROJECT_PATH = os.path.abspath(os.path.join(BASIC_PATH, '../'))
sys.path.append(PROJECT_PATH)
env_choose_path = os.path.join(BASIC_PATH, 'base_config', 'env_choose.ini')
# 获取业务标示：hh or hhi
try:
    current_business_index = input_team_name.index('-b')
    current_business = input_team_name[current_business_index + 1]
except ValueError:
    current_business = "hh"
# 获取环境 QA or SIM
try:
    current_evn_index = input_team_name.index('-e')
    current_evn = input_team_name[current_evn_index + 1]
except ValueError:
    current_evn = "QA"


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Choose current environment")
    parser.add_argument("-b", dest='business', help="hh or hhi", default='hh')
    parser.add_argument("-e", dest='env', help="QA or SIM", default='QA')
    parser.add_argument("-u", dest='user', help="user", default='lrq')
    parser.add_argument("-j", dest='jira_id', help="jira_id", default='')
    parser.add_argument("-t", dest='team_name', help="team_name", default='')
    args = parser.parse_args()
    # choose_env = args.env
    choose_user = args.user
    # jira_id = args.jira_id
    business = args.business
    jira_id = args.jira_id
    if jira_id.lower() == 'sim':
        args.env = 'SIM'
    choose_env = args.env

    # 将命令行参数写入env_choose.ini文件中
    cof = configparser.ConfigParser()
    cof.read(env_choose_path, encoding='utf-8')
    cof.set(section="run_evn_name", option="current_business", value=args.business.lower())
    cof.set(section="run_evn_name", option="current_evn", value=args.env.upper())
    cof.set(section="run_user_name", option="default_user", value=args.user.lower())
    cof.set(section="run_jira_id", option="huohua-podenv", value=args.jira_id.upper())
    cof.set(section="run_evn_name", option="current_team", value=args.team_name.upper())
    with open(env_choose_path, 'w') as fw:  # 循环写入
        cof.write(fw)

    if jira_id:
        print("running jira_id is:【{}】【{}】【{}】".format(business, TEAM_NAME, jira_id))
    else:
        print("running environment is: 【{}】【{}】【{}】".format(business, TEAM_NAME, choose_env))

    from base_framework.main import main, kill_pid
    kill_pid()
    main()
