#!/usr/bin/python3
# -*- coding: utf-8 -*-
from __future__ import print_function


"""\
Given a CD TOC ID (as created by cdread),
rename to a release group.
"""

from sqlmix import Db

import sys
import os
import click
from mpdb.model import Dir
from mpdb.exceptions import NextPlease
import musicbrainzngs as mbz

pj = os.path.join

mbz.set_useragent(
    "mpdb",
    "0.1",
    "https://github.com/smurfix/mpdb/",
)

@click.command()
@click.option("--dest", "-D", help="directory", default="/d/sound/mb")
@click.option("--file", "-o", help="output file", default="-")
@click.option("--no-database", "-n", is_flag=True, help="don't use the local database")
@click.option("--no-musicbrainz", "-N", is_flag=True, help="don't talk to MusicBrainz ")
@click.argument("args", nargs=-1)
def main(dest, file, args, no_database, no_musicbrainz):
    if dest is not None:
        pass
    if not args:
        raise click.BadArgumentUsage("Need at least one directory to read")
    if not os.path.isdir(dest):
        raise RuntimeError("Not a directory: " + repr(dest))

    if no_database:
        db = None
    else:
        db = Db("musicbrainz")
    if no_musicbrainz:
        mb = None
    else:
        mb = mbz

    if file == "-":
        OUT = sys.stdout
    else:
        OUT = open(file, "w")

    print("""\
info_begin
format: 1
mpd_version: 0.16.7
fs_charset: UTF-8
tag: Artist
tag: Album
tag: Title
tag: Track
tag: Name
tag: Genre
tag: Date
tag: Composer
tag: Performer
tag: Disc
info_end
""", end="", file=OUT)

    for d in args:
        try:
            fns = Dir(dest, d, db, mb)
            fns.load_dir()
            fns.mpd_info(stream=OUT)
        except NextPlease:
            pass

    if OUT is not sys.stdout:
        OUT.close()


if __name__ == "__main__":
    main()
