#!/usr/bin/env python3

import argparse
import logging
from sys import exit

from libBGG.BGGAPI import BGGAPI
from libBGG.BGGCache import BGGCache

log = logging.getLogger(__name__)

if __name__ == '__main__':
    desc = ('Query BGG for boardgames and related information. All arguments may be given '
            'and given multiple times.')

    ap = argparse.ArgumentParser(description=desc)
    ap.add_argument('-g', '--game', dest='game', action='append', help='Name of game.')
    ap.add_argument('-G', '--guild', dest='guild', action='append',
                    help='ID of guild. (bgg does not support guild by name search.')
    ap.add_argument('-u', '--user', dest='user', action='append', help='Name of BGG user.')
    ap.add_argument('-c', '--collection', dest='collection', action='append', help='User\'s'
                    ' collection')
    ap.add_argument('-C', '--cache', dest='cache', help='Path to cache. If given look in '
                    'cache first, then fetch from BGG. Otherwise always fetch from BGG.'
                    ' collection. If --forcefetch is given, force a fetch into the cache.')
    ap.add_argument('-f', '--forcefetch', dest='forcefetch', help='If given, force a refetch '
                    'of any data. This argument does nothing if a cache is not given.',
                    action='store_true')
    ap.add_argument("-l", "--loglevel", dest="loglevel",
                    help="The level at which to log. Must be one of "
                    "none, debug, info, warning, error, or critical. Default is none. ("
                    "This is mostly used for debugging.)",
                    default='none', choices=['none', 'all', 'debug', 'info', 'warning',
                                             'error', 'critical'])
    args = ap.parse_args()

    if args.game is None and args.guild is None and args.user is None and args.collection is None:
        ap.print_help()
        exit(1)

    logLevels = {
        'none': 100,
        'all': 0,
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }
    log_format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
    log_datefmt = '%m-%d %H:%M:%S'
    logging.basicConfig(format=log_format, datefmt=log_datefmt,
                        level=logLevels[args.loglevel])
    
    if args.cache is not None:
        bgg = BGGAPI(BGGCache(args.cache))
    else:
        bgg = BGGAPI()

    query_map = {
        bgg.fetch_boardgame: args.game,
        bgg.fetch_guild: args.guild,
        bgg.fetch_user: args.user,
        bgg.fetch_collection: args.collection,
    }
    for func, queries in query_map.items():
        if queries:
            for query in queries:
                item = func(query, forcefetch=args.forcefetch)
                if item is None:
                    print('%s: not found. No connection or not in cache if given.' % query)
                    continue

                item.dump()
