#!/usr/bin/python
# -*- coding: utf-8 -*-
# 
# By Caspar Verhey, 2009 <caspar@verhey.net>
#
# Heavily based on work by Danilo Segan, 2004 <danilo@kvota.net>
# and documentation from http://solonweb.free.fr/tech.htm
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# It is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import sys, os, math, shutil, struct, hashlib, zlib, re

sys.path.append("pylips2")

from mutagen.easyid3 import EasyID3
from mutagen.mp3 import MP3

#== set settings ========================================

#/Music/DarkMoor/0-Halloft/9-QuestForE.mp3
musicdir = 'Music'
datadir  = 'System/data'

files = []
errors = []

#== set data format =====================================

recordsize = 408

field_offsets = { "hidden" : 0, # 0/1
                  "reserved1" : 4, # 0
                  "reserved2" : 8, # 0
                  "path" : 12,
                  "name" : 68,
                  "bitrate" : 100, # bits per second
                  "samplerate" : 104, # bits per second
                  "duration" : 108, # seconds
                  "artist" : 112,
                  "album" : 192,
                  "genre" : 272,
                  "title" : 312,
                  "tracknumber" : 392, # track number
                  "year" : 396,
                  "size" : 400, # file size in bytes
                  "source" : 404 # reserved, 0
                  }

#== start program =======================================

def main():
  get_files(musicdir)

  write_dat(files)

  indexes = {
    "@DEV" : "hidden",
    "FNAM" : "name",
    "FPTH" : "path",
    "TALB" : "album",
    "TCON" : "genre",
    "TIT2" : "title",
    "TPE1" : "artist",
    "TRCK" : "tracknumber",
    "XSRC" : "source"
    }

  for name in indexes:
    filename = os.path.join(datadir, 'DB5000_' + name + '.IDX')
    write_index(files, filename, indexes[name])

  count = len(files)

  print "%d files added." % count

  print "following errors occurred:"

  for error in errors:
    print error

  f = open(os.path.join(datadir, 'DB5000.HDR'), "r+")

  f.seek(1036)
  f.write(struct.pack("L", recordsize))
  f.seek(1040)
  f.write(struct.pack("L", count))
  f.seek(1604)
  f.write(struct.pack("L", int((field_offsets["name"] - field_offsets["path"])/2)))
  f.seek(2148)
  f.write(struct.pack("L", int((field_offsets["bitrate"] - field_offsets["name"])/2)))

  offs = struct.pack("14L",
                   field_offsets["reserved2"], 
                   field_offsets["path"], 
                   field_offsets["name"], 
                   field_offsets["bitrate"], 
                   field_offsets["samplerate"], 
                   field_offsets["duration"], 
                   field_offsets["artist"], 
                   field_offsets["album"], 
                   field_offsets["genre"], 
                   field_offsets["title"], 
                   field_offsets["tracknumber"], 
                   field_offsets["year"], 
                   field_offsets["size"], 
                   field_offsets["source"])

  f.seek(12964)
  f.write(offs)

#== scan for MP3's ======================================

def get_files(dir):
    # find mp3's and adjust recordsize if neccesary
    global field_offsets
    global files
    global errors
    for file in os.listdir(dir):
        fullname = os.path.join(dir, file)
        if os.path.isdir(fullname):
            get_files(fullname)
        else:
            print fullname
            try:
              audio = MP3(fullname, ID3=EasyID3)
            except:
              print "[skip] not an MP3-file"
              errors.append("[skip] not an MP3-file " + fullname)
              continue
            
            track = {}
            track['bitrate']     = int(audio.info.bitrate)
            track['sample_rate'] = int(audio.info.sample_rate)
            track['duration']    = int(math.ceil(audio.info.length))
            try:
              track['artist']    = audio['artist'].pop()
            except:
              track['artist']    = u'No Artist'
            try:
              track['album']     = audio['album'].pop()
            except:
              track['album']     = u'No Album'
            try:
              track['genre']     = audio['genre'].pop()
            except:
              track['genre']     = u'No Genre'
            try:
              track['title']     = audio['title'].pop()
            except:
              track['title']     = u'No Title'
            try:
              track['tracknumber'] = int(audio['tracknumber'].pop())
            except:
              track['tracknumber'] = 0
            try:
              track['year']      = int(audio['date'].pop())
            except:
              track['year']      = 0
            
            # new directory: musicdir (max. 5) / artist (max. 8) / year - album (max. 11) -> together max. 27 incl. slashes
            #newdir = os.path.join( musicdir, track['artist'][:8].strip(), (str(track['year'])+'-'+track['album'])[:10].strip() )
            newdir = os.path.join( musicdir, plainchars( track['artist'][:8].strip() ), plainchars( (str(track['year'])+'-'+track['album'])[:10].strip() ) )

            # new filename: track - title (max 12) + .mp3 (4) -> together max. 16
            #newfile = ( str(track['tracknumber'])+'-'+track['title'] )[:12].strip() + '.mp3'
            newfile = ( plainchars( str(track['tracknumber'])+'-'+track['title'] )[:12].strip() ) + '.mp3'

            try:
              movetonewfolder(fullname, newdir, newfile)
            except:
              print "[skip] could not move file"
              errors.append("[skip] could not move file " + fullname + " to " + os.path.join(newdir, newfile) )
              continue

            track['file'] = os.path.join(newdir, newfile)
            track['path'] = newdir
            track['name'] = newfile
            track['size'] = int(os.path.getsize(track['file']))
            track['hidden'] = 0
            track['source'] = 0

            trackid = len(files)
            track['trackid'] = trackid
            files.append(track)

            #print track
            #print "[done] moved to", track['file']

#== put files in new folder =============================

def movetonewfolder(oldfile, newdir, newfile):
  if (os.path.isdir(newdir) == False):
    os.makedirs(newdir)
  shutil.move(oldfile, os.path.join(newdir, newfile))

#== strip invalid characters from filename ==============

def plainchars(str):
  return re.sub("[^a-zA-Z0-9\-_ ]",'',str)

#== define data format ==================================

def field_format():
    format = "LLL" # hidden, reserved1, reserved2
      
    # file path
    len = field_offsets["name"] - field_offsets["path"]
    format += str(len) + "s"
    
    # file name
    len = field_offsets["bitrate"] - field_offsets["name"]
    format += str(len) + "s"
    
    format += "LLL" # bitrate, samplerate, duration
    
    # artist
    len = field_offsets["album"] - field_offsets["artist"]
    format += str(len) + "s"
    
    # album
    len = field_offsets["genre"] - field_offsets["album"]
    format += str(len) + "s"
    
    # genre
    len = field_offsets["title"] - field_offsets["genre"]
    format += str(len) + "s"
    
    # title
    len = field_offsets["tracknumber"] - field_offsets["title"]
    format += str(len) + "s"
    
    format += "LLLL" # track number, year, size (bytes), source
    return format

#== write DB5000.DAT ====================================

def write_dat(files):
    # write DB5000.DAT file listing all the MP3 files
    f = open(os.path.join(datadir, "DB5000.DAT"), "w")
    for file in files:
        format = field_format()
        path = file['path'] + "\\"
        path = path.replace("/", "\\")

        data = struct.pack( format,
                                0, # hidden
                                0, # reserved 1
                                0, # reserved 2
                                path.encode('UTF-16-LE'),
                                file['name'].encode('UTF-16-LE'),
                                int(file['bitrate']),
                                int(file['sample_rate']),
                                int(file['duration']),
                                file['artist'].encode('UTF-16-LE'),
                                file['album'].encode('UTF-16-LE'),
                                file['genre'].encode('UTF-16-LE'),
                                file['title'].encode('UTF-16-LE'),
                                int(file['tracknumber']),
                                int(file['year']),
                                int(file['size']),
                                0 # source
                                )
        f.write(data)

    f.close()

#== debugging function ==================================

def printout(files):
    # Debugging function, print out DAT files
    global recordsize
    print recordsize
    for fil in files:
        f = open(fil, "r+")
        format = field_format()
        trackid = 0
        data = f.read(recordsize)
        while data:
            tupl = struct.unpack(format, data)
            (hidden, res1, res2, path, name, bitrate, samplerate, duration,
             artist, album, genre, title, tracknumber, year, size, source ) = tupl
            
            print "trackid: %d" % trackid
            print "hidden: %d" % hidden
            print "res1: %d" % res1
            print "res2: %d" % res2
            print "path: %s" % path
            print "name: %s" % name
            print "bitrate: %d" % bitrate
            print "samplerate: %d" % samplerate
            print "duration: %d" % duration
            print "artist: %s" % artist
            print "album: %s" % album
            print "genre: %s" % genre
            print "title: %s" % title
            print "track: %d" % tracknumber
            print "year: %d" % year
            print "size: %d" % size
            print "source: %d" % source
            data = f.read(recordsize)

            trackid += 1
                
        f.close()

#== sort fields =========================================

def sort_table_by_field(dct, field):
    skeys = dct
    skeys.sort(lambda m,n: cmp( m[field], n[field] ) or cmp( n['trackid'], m['trackid'] ) )
    return skeys

#== create .idx-files ===================================

def write_index(files, filename, field):
    print "Sorting by field '%s'..." % (field)
    sortedfiles = sort_table_by_field(files, field)
    f = open(filename, "wb")
    for fil in sortedfiles:
        fileid = fil['trackid']
        try:
            value = fil[field].encode('ascii','replace')
        except:
            value = str(fil[field])
        hsh = abs(zlib.crc32(value))
        data  = struct.pack("LLL", 0, fileid, hsh)
        f.write(data)
    f.close()

#========================================================

if __name__ == "__main__":
  main()

#printout([os.path.join(datadir,'DB5000.DAT')])