import sys
import os

if len(sys.argv) > 3:
    sys.path.append(os.path.abspath(sys.argv[3]))
if len(sys.argv) < 3:
    print('python basic_edit_test.py <config> <prefix> [<include path>]\n')
    sys.exit()

# Create a config file containing:
# host = 'test.wikipedia.org'
# path = '/w/'
# ext = '.php'
# username = 'Bryan'
# password = 'xyz'

prefix = sys.argv[2]

# import cgitb; cgitb.enable(format = 'text')
try:
    import apiedit as mwclient
except ImportError:
    import mwclient
site = mwclient.ex.ConfiguredSite(sys.argv[1])
site.compress = False

print('Running configured site', sys.argv[1])

page = site.Pages[prefix + '/text1']

print('Editing page1')

text1 = u"""== [[Test page]] ==
This is a [[test]] page generated by [http://mwclient.sourceforge.org/ mwclient].
This test is done using the [[w:mw:API]]."""
comment1 = 'Test page1'
page.edit(text1, comment1)

rev = page.revisions(limit=1, prop='timestamp|comment|content').next()
assert rev['comment'] == comment1, rev
assert rev['*'] == rev['*'], rev
print('Page edited on', rev['timestamp'])
print('Links:', list(page.links(generator=False)))
print('External links:', list(page.extlinks()))

print('Uploading image')
site.upload(open('test-image.png', 'rb'), prefix + '-test-image.png', 'desc', ignore=True)
print('Uploading image for the second time')
site.upload(open('test-image.png', 'rb'), prefix + '-test-image.png', 'desc', ignore=True)
image = site.Images[prefix + '-test-image.png']
print('Imageinfo:', image.imageinfo)
history = list(image.imagehistory())
print('History:', history)

print('Deleting old version')
archivename = history[1]['archivename']
image.delete('Testing history deletion', oldimage=archivename)
print('History:', list(image.imagehistory()))

text = page.text()
text += '\n[[Image:%s-test-image.png]]' % prefix
page.edit(text, 'Adding image')
print('Images:', list(page.images(generator=False)))
print('Cleaning up')

image.delete('Cleanup')
page.delete('Cleanup')

print('Done')
