#!/usr/bin/env python

import click
import re
import json
from string import Template

from discogs_finder import *


@click.command(context_settings=dict(
    ignore_unknown_options=True,
))
@click.option('--u', 'user', prompt='Your discogs user name',
              help='Your discogs user name')
@click.option('--v', 'verbose', flag_value=True,
              default=False,
              help='Verbose output dumping the whole json-file')
@click.option('--p', 'verbose', flag_value=False, 
              help='Pretty output')
@click.argument('querry', nargs=-1, type=click.UNPROCESSED)
def finder(user, querry, verbose=False):
    """ FIND Every Release:
    
    Find the releases in your collection with an easy
    key value search.  The script 'discogs-finder' 
    accepts one option that is specified in form of a
    'key=value' format.  If the value contains 
    whitespace, the argument must be contained in 
    "quotation marks".
    
    \b
    Examples:
        $ discogs-tagger --u titm6her name="Keith Jarrett"
        $ discogs-tagger --u titm6her name="ABC Impulse!"
        $ discogs-tagger --u --v titm6her title=Shades
        $ discogs-tagger --u titm6her id=3318191
    """

    p_arg = re.compile(r'(\w+)=([\w\s]+)')
    match = p_arg.match(querry[0])
    if match:
        value = match.group(2)
        q = {match.group(1): match.group(2)}
    else:
        raise click.BadParameter('Could not match your querry to value=key')
    
    click.echo('Searching for ' + str(q))
    data = load_data(user)
    
    p_repl = re.compile(value, flags=re.IGNORECASE)
    result = []
    for r in data:
        f, a, v = found_in_release(r, None, **q)
        if f:
            if verbose:
                s = json.dumps(r, indent=2)
                s = p_repl.sub(r'${value}', s)
                temp = Template(s)
                style = click.style(value, fg='green', bold=True)
                s = temp.safe_substitute(value=style)
            else:
                v = p_repl.sub(r'%s', unicode(v), count=1)
                rs = release_string(r)
                s = '%d)\t%s\n\t%s = %s' % (len(result) + 1,
                                        rs, '.'.join(a), v)
                s = s % click.style(value, fg='green', bold=True)
            result.append(s)
    click.echo('\n'.join(result))
    
if __name__ == '__main__':
    finder()