import json
import sys
import urllib.request
from datetime import datetime
from symbols.file_utils import make_path, load

if __name__ == '__main__':

    seeds = [31, 33, 76, 82, 92]
    directory = datetime.today().strftime('%Y%m%d')
    directory = '20191119'
    directory = '20191204_full'
    directory = '20191230'
    directory = '20200106'
    task_id = 0
    task_dir = make_path(directory, task_id)
    partition_dir = make_path(task_dir, 'partitioned_options')
    operator_dir = make_path(task_dir, 'learned_operators')
    pddl_dir = make_path(task_dir, 'pddl')

    with open(make_path(pddl_dir, 'linked.pddl'), 'r') as file:
        domain = file.read()

    with open(make_path(pddl_dir, 'problem.pddl'), 'r') as file:
        problem = file.read()

    data = {'domain': domain,
            'problem': problem}

    params = json.dumps(data).encode('utf8')
    request = urllib.request.Request('http://solver.planning.domains/solve', headers={'Content-Type': 'application/json'},
                                 data=params)


    proxy = urllib.request.ProxyHandler({'http': r'http://ds\a0029938:Password250891@proxyad.wits.ac.za:80'})
    auth = urllib.request.HTTPBasicAuthHandler()
    opener = urllib.request.build_opener(proxy, auth, urllib.request.HTTPHandler)
    urllib.request.install_opener(opener)

    resp = json.loads(urllib.request.urlopen(request).read())

    result = resp['result']

    print(result['output'])

    if result['parse_status'] == 'ok':

        print('\n'.join([act['name'] for act in resp['result']['plan']]))

        print()

        print('\n\n'.join([act['action'] for act in resp['result']['plan']]))

    # if result['val_status'] == 'valid':
    #     print("PDDL okay!")
    #     print(resp['val_stdout'])
    # elif resp['val_status'] == 'err':
    #     print(resp['val_stderr'])




    # with open(sys.argv[3], 'w') as f:
    #     f.write('\n'.join([act['name'] for act in resp['result']['plan']]))
