import sys,os
from ID3 import ID3

sys.path.append("./")
from index import *

ID3FIELDS = ["TITLE", "ALBUM", "ARTIST"]

@typechecked(str)
def metadataFromID3(filename):
    """Return a metadata block built from the ID3 tags of the
    specified file."""
    id3 = ID3(filename)

    m = Metadata()

    for field in ID3FIELDS:
        try:
            val = id3[field]
            m.setMetadatum(Metadatum(field.lower(), val, True))
        except KeyError:
            pass
    m.setMetadatum(Metadatum("filename", filename, False))

    return m

def metadataFromMP3Files(root):
    """Return a list of metadata blocks, built from the ID3 tags of
    all the Mp3 files in the specified directory."""
    metadatas = []
    for dirpath, dirname, filenames in os.walk(root):
        for filename in filenames:
            if filename.endswith(".mp3"):
                md = metadataFromID3(os.path.join(dirpath, filename))
                if md.getMetadatum("title") != None:
                    # Ignore anything without a title. Don't know
                    # where these come from exactly.
                    metadatas.append(md)
    return metadatas

            

K=3
svr = IndexCollection()
md = metadataFromMP3Files("/usr/home/dan/music")

for x in md:
    for kssss in x.getKSSSets(K):
        svr.addToIndex(indexNameFromSet(kssss), x)

print "Files:", len(md)
print "Keywords:", sum(len(x.getKeywords()) for x in md)
svr.showStats()

q = Query()
q.addKeyword("title", "god")
q.addKeyword("title", "wrote")
q.addKeyword("title", "in")
q.addKeyword("title", "lisp")
q.addKeyword("title", "code")
res = svr.search(indexNameFromSet(q.getIndexKeywordSet(K)), q)
for x in res:
    print x
