#!/usr/bin/env python
""" This is a CLI script for editing the properties of a badge.  """

import __main__
__main__.__requires__ = __requires__ = ["tahrir-api", "sqlalchemy>=0.7"];
import pkg_resources
pkg_resources.require(__requires__)

import argparse
import transaction
import sys

from tahrir_api.dbapi import TahrirDatabase

import fedmsg.config

import fedbadges.utils


def parse_args():
    parser = argparse.ArgumentParser(__doc__)
    parser.add_argument('--badge', default=None, help="A badge id")
    # XXX - Note, this script intentionally does not allow changing the badge-id
    # of a badge.  Some things depend on that field as a foreign key and it is
    # unclear what would break if we changed that.
    parser.add_argument('--name', default=None, help='Name..')
    parser.add_argument('--description', default=None, help='Description..')
    parser.add_argument('--criteria', default=None, help='Criteria link')
    parser.add_argument('--image', default=None, help='Image link')
    parser.add_argument('--tags', default=None, help='Badge Tags')
    args = parser.parse_args()
    if not args.badge:
        print "You must specify a badge id."
        sys.exit(1)
    if not args.name and not args.description and not args.criteria and not args.image and not args.tags:
        print "You must specify either name, description or criteria, tags or image to edit."
        sys.exit(1)
    return args


def initialize():
    fm_config = fedmsg.config.load_config()
    fm_config['cert_prefix'] = 'fedbadges'
    fm_config['name'] = 'relay_inbound'
    fm_config['active'] = True
    fedmsg.init(**fm_config)
    uri = fm_config['badges_global']['database_uri']
    tahrir = TahrirDatabase(
        uri,
        notification_callback=fedbadges.utils.notification_callback,
    )
    return tahrir


def main(tahrir, badge_id, name, description, criteria, image, tags):
    badge = tahrir.get_badge(badge_id)

    if not badge:
        print "No such badge %r" % badge_id
        sys.exit(1)

    transaction.begin()

    if name:
        badge.name = name
        print "Setting name on %r to %r" % (badge_id, name)

    if description:
        badge.description = description
        print "Setting description on %r to %r" % (badge_id, description)

    if criteria:
        badge.criteria = criteria
        print "Setting criteria on %r to %r" % (badge_id, criteria)

    if image:
        badge.image = image
        print "Setting image on %r to %r" % (badge_id, image)

    if tags:
        badge.tags = tags
        print "Setting tags on %r to %r" % (badge_id, tags)

    tahrir.session.commit()
    transaction.commit()


if __name__ == '__main__':
    args = parse_args()
    tahrir = initialize()
    main(tahrir, args.badge, args.name, args.description, args.criteria,
         args.image, args.tags)
