#!/usr/bin/env python
# Upload a file to a recent MediaWiki using the API.
#
# The configuration file ~/.config/wiki-upload.yaml must contain Wiki site
# information and credentials. For example:
#
#    ---
#    site: awesomewiki.com
#    https: yes
#    site_opts:
#      path: /wiki/
#    username: UploadBoat
#    password: VeRySeCuR3
#

from __future__ import division, print_function
import argparse
import mwclient
import os.path
import termcolor
import yaml


def login():
    config = yaml.load(open(os.path.expanduser('~/.config/wiki-upload.yaml')))

    mw_site = ('https', config['site']) if config['https'] else config['site']
    mw_site_opts = config['site_opts'] if 'site_opts' in config else {}
    mw_site_opts['clients_useragent'] = 'wiki-upload'

    site = mwclient.Site(mw_site, **mw_site_opts)
    site.login(config['username'], config['password'])

    return site


def parse_args():
    parser = argparse.ArgumentParser(
        description='Upload a file to a recent MediaWiki using the API.')
    parser.add_argument('images', metavar='image.jpg', nargs='+',
                        help='an image to upload')
    parser.add_argument('-d', '--description', required=True,
                        help='description of the images')
    args = parser.parse_args()

    return args


def main():
    site = login()

    args = parse_args()
    for image in args.images:
        destination_name = os.path.basename(image)

        print('Uploading {} ... '.format(destination_name))
        ret = site.upload(open(image), destination_name, args.description)

        color = 'green' if ret['result'] == 'Success' else 'yellow'
        print(termcolor.colored('  {}'.format(ret['result']), color))
        if 'warnings' in ret:
            for warning, what in ret['warnings'].items():
                print(termcolor.colored('  {}: {}'.format(warning, what),
                                        'yellow'))

main()