import argparse
import glob
import os
from concurrent.futures.thread import ThreadPoolExecutor
from urllib.parse import urlparse, urljoin
import requests
import yaml


def create_regression(cfg_filename, url):
    with open(cfg_filename, encoding='utf-8') as f:
        resp = requests.post(url, data=f.read().encode('utf-8'))
        if resp.status_code != 200:
            print("Warning: Response {}:\n{}\nConfig: {}".format(resp.status_code,
                                                                 resp.content,
                                                                 cfg_filename))


def edit_regression(cfg_filename, api):
    with open(cfg_filename, encoding='utf-8') as f:
        parsed = yaml.full_load(f)
        cfg, name = parsed['config'], parsed['config']['name']
        url = urljoin(urljoin(api, 'regression/'), name)
        resp = requests.put(url, data=yaml.dump(cfg, allow_unicode=True))
        if resp.status_code != 200:
            print(url)
            print("Warning: Response {}:\n{}\nConfig: {}".format(resp.status_code,
                                                                 resp.content,
                                                                 cfg_filename))


if __name__ == '__main__':
    CREATE_REGRESSION = 'regression/create'
    CONFIG_WILDCARD = '*.yaml'
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', '--api', help='luna api base url', action='store',
                        default='http://dev-back.luna.yandex-team.ru')
    parser.add_argument('config_files_folders', metavar='C', type=str, nargs='+',
                        help='Folder(s) containing LUNA regression config(s), yaml formatted')
    parser.add_argument('-t', '--threads', help='number of threads', action='store', type=int, default=5)
    parser.add_argument('-e', '--edit', help='edit existing regression(s)', action='store_true', default=False)
    args = parser.parse_args()
    assert urlparse(args.api)[0], 'Wrong url format: {}'.format(args.api)
    url = urljoin(args.api, CREATE_REGRESSION)
    config_files = {file for folder in args.config_files_folders
                    for file in glob.glob(os.path.join(folder, CONFIG_WILDCARD))}

    with ThreadPoolExecutor(max_workers=args.threads) as executor:
        if args.edit:
            [executor.submit(edit_regression, cfg_file, args.api) for cfg_file in config_files]
        else:
            [executor.submit(create_regression, cfg_file, url) for cfg_file in config_files]
    #
    # for f in config_files:
    #     create_regression(f, url)