#!/usr/bin/python3
import click
import os
from  onebrain.utils.yamltool  import YamlConfig
from   onebrain.utils.requeststool import  RequestsTool
from onebrain.utils.configtool import OnebrainConfig
from onebrain.dataset import DataSet
from onebrain.utils.config import BASE_DIR,INI_FILE
from onebrain.utils.FileUpload import  getAllFiles
@click.group()
def onebrain():
    pass

@click.command()
@click.option("-server",  prompt="server", help="the Url of onebrain server")
@click.option("-username", prompt="username",
                  help="username")
@click.option("-password", prompt="password", help="password")
def login(server, username, password):
    if server.startswith("http") == False:
        server = "http://"+server
    base_url = "/api/1/auth/cli/login"
    login_url = server + base_url
    params ={
        "password": password,
        "username": username
    }
    rq = RequestsTool()
    re = rq.post(login_url, params)
    print(re)
    if re['code'] == 200:
        print('token' + re['data']['token'])
        oc = OnebrainConfig()
        oc.set_server(server)
        oc.set_token(re['data']['token'])
    else:
        print(re['msg'])

    return

@click.command()
@click.option("-file",  prompt="filename", help="the filename of config ")
def create(file):
    of = OnebrainConfig()
    token =of.get_token()
    if token == None:
        print("没有登录 ")
        return
    yaml_config = YamlConfig()
    yaml = yaml_config.load(file)
    if 'kind' in yaml:
      if yaml['kind'].lower() == 'dataset'.lower():
         dataset = DataSet(yaml)
         dataset.create()
    return

@click.command()
@click.option("-file",  prompt="filename", help="the filename of config ")
def update(file):
    of = OnebrainConfig()
    token = of.get_token()
    if token == None:
        print("没有登录 ")
        return
    yaml_config = YamlConfig()
    yaml = yaml_config.load(file)
    if 'kind' in yaml:
        if yaml['kind'].lower() == 'dataset'.lower():
            dataset = DataSet(yaml)
            dataset.update()
    return
@click.command()
@click.option("-file",  prompt="filename", help="the filename of config ")
def delete(file):
    of = OnebrainConfig()
    token = of.get_token()
    if token == None:
        print("没有登录 ")
        return
    yaml_config = YamlConfig()
    yaml = yaml_config.load(file)
    if 'kind' in yaml:
        if yaml['kind'].lower() == 'dataset'.lower():
            dataset = DataSet(yaml)
            dataset.delete()
    return
@click.command()
def clean():
    fileNames =getAllFiles(BASE_DIR)
    for item in fileNames:
        if item.endswith(INI_FILE):
            continue
        else:
            os.remove(item)
onebrain.add_command(login)
onebrain.add_command(create)
onebrain.add_command(update)
onebrain.add_command(delete)
onebrain.add_command(clean)
if __name__ == '__main__':
    if os.path.exists(BASE_DIR) == False:
        os.mkdir(BASE_DIR)
    onebrain()