import os, json
from mwclient import Site
from pprint import pprint
from functions import update_json

site = Site(host='hub.xpub.nl/sandbox', path='/itchwiki/')
wd = os.path.dirname(os.path.abspath(__file__)) # working directory

imgdir = os.path.join(wd, 'images')
os.makedirs(imgdir, exist_ok=True) # create images/ dir

imgsjson_fn = os.path.join(wd, 'images.json')



with open(os.path.join(wd, 'login.txt'), 'r') as login:  # read login user & pwd
    loginlines = login.read()
    user, pwd = loginlines.split('\n')
    site.login(username=user, password=pwd)  # login to wiki

with open(imgsjson_fn, 'r') as imgsjson_file:
    images_info = json.load(imgsjson_file)

img_info = images_info["File:CCF 003017.jpg"]

print(img_info)
page_name = img_info['name']
page = site.pages[page_name]
print(page)
pprint(page.__dict__)
print(dir(page))
text = page.text()
used_in = list(page.imageusage())
print(text, used_in)
# response = site.api(action='browsebysubject', subject=page_name)
# for q in response['query']['data']:
#     print(q['property'], q['dataitem'])
#     print(q)
# print('result:', response['query']['data'][0]['item'])
# print('keys', response['query'].keys())

response = site.ask(query='[[Date::+]]|?Date', title=page_name)
print(response)
# import pdb; pdb.set_trace()
for r in response:
    print('response', r)
    for title, data in r.items():
        print(data)
        # import pdb; pdb.set_trace()
        print(type(data))
        if type(data) not in [str, int]:
            for k, item in data.items():
                print('item', k, item[k])
                for subitem in data.items():
                    print('subitem', subitem, )
       # for k, v in data['printouts']:
       #     print(k,v)
# action=smwbrowse&browse=page&params={ "limit": 10, "offset": 0, "search": "Main", "fullText": true, "fullURL": true }
# for page in site.pages(page_name):
#     print(page)


#
# for img_key, img_info in images_info.items():
#     if n < 4:
#         print(img_info)
#         page_name = img_info['name']
#         page = site.pages(page_name)
#         print(page)
#         print('\n')