#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import os.path
import sys
import glob
import shutil
import eyeD3
import rfZenHan

l_original = u"オリジナル"
l_origcovoer = u"オリジナルカバー"
l_vclcovoer = u"VOCALOIDカバー"
l_humanoid = u"歌ってみた"

normalize = rfZenHan.normalizeI()
cifs = rfZenHan.normalizeCIFSI()
syscode = ""
pathsep = ""
storage = ""
artists = []

def parseMP3(path):
	upath = unicode(path, syscode)
	filename = os.path.basename(upath)[0:-4]
	directories = os.path.dirname(upath)
	composer = os.path.basename(directories)
	comment = ""
	title = ""
	artist = ""
	original = ""
	category = ""
	subdir = "audio"

	ss = filename.split("_")
	if len(ss) < 3:
		return
	if ss:
		comment = ss.pop(0)
	if ss:
		title = ss.pop(0)
	if ss:
		artist = ss.pop(0)
	if ss:
		original = ss.pop(0)
	if ss:
		category = ss.pop(0)
	mp3fn = title

	composer = normalize.conv(composer).strip()
	comment = normalize.conv(comment).strip()
	title = normalize.conv(title).strip()
	artist = normalize.conv(artist).strip()
	original = normalize.conv(original).strip()
	category = normalize.conv(category).strip()

	if not category:
		if not original:
			category = l_original
		else:
			origartist = inArtists(artist)
			origvlcp = inArtists(original)
			if origartist:
				original = origvlcp
				category = l_humanoid
				subdir = l_humanoid
			elif origvlcp:
				original = origvlcp
				category = l_origcovoer
			else:
				category = l_vclcovoer
	if not original:
		original = composer
	else:
		mp3fn += "_" + artist
		if artist != composer:
			mp3fn += "_" + composer
	if artist:
		category += "(" + artist + ")"
	if len(comment) >= 2:
		comment = comment[2:len(comment)]

	mp3fn = cifs.conv(mp3fn + ".mp3")
	setID3(path, title, artist, composer, original, comment, category)
	moveStorage(path, storage + pathsep + subdir, mp3fn)

def setID3(path, title, artist, composer, original, comment, category):
	tag = eyeD3.Tag()
	tag.link(path)
	tag.remove(eyeD3.ID3_V1)
	tag.remove(eyeD3.ID3_V2)
	tag.clear()
	tag.header.setVersion(eyeD3.ID3_V2_3)
	tag.setTextEncoding(eyeD3.UTF_16_ENCODING)

	tag.setArtist(composer)
	tag.setTitle(title)
	tag.setAlbum(category)
	#tag.setTextFrame("TCON", artist)
	tag.setTextFrame("TOPE", original)
	#tag.addComment(comment, comment, "JPN")
	tag.setTextFrame("TRCK", comment)
	tag.update()

def moveStorage(path, storage, file):
	upath = unicode(path, syscode)
	filename = os.path.basename(upath)
	directories = os.path.dirname(upath)

	if not os.path.exists(storage):
		os.mkdir(storage)
	if not file:
		file = filename
	store = (storage + pathsep + file).encode(syscode)
	print path + " > " + store
	shutil.copy2(path, store)
	os.chmod(store, 0444)

	done = (directories + pathsep + "done").encode(syscode)
	if not os.path.exists(done):
		os.mkdir(done)
	shutil.move(path, done + pathsep + filename.encode(syscode))

def inArtists(s):
	cand = ""
	for a in artists:
		if s == a:
			return a
		if a.find(s) >= 0:
			cand = a
	return cand

def setArtists(path):
	for f in os.listdir(path):
		if os.path.isdir(f):
			composer = unicode(f, syscode)
			composer = normalize.conv(composer)
			artists.append(composer)

if __name__ == "__main__":
	if os.name == "dos" or os.name == "nt":
		syscode = "cp932"
		pathsep = "\\"
	else:
		syscode = "utf-8"
		pathsep = "/"
	storage = ".." + pathsep + "storage"
	if len(sys.argv) > 1:
		storage = storage[1]
	storage = unicode(storage, syscode)
	if not os.path.exists(storage):
		os.mkdir(storage)

	setArtists(".")
	for f in os.listdir("."):
		for mp3 in glob.glob(f + pathsep + "*.mp3"):
			parseMP3(mp3)
		for flv in glob.glob(f + pathsep + "*.flv"):
			moveStorage(flv, storage + pathsep + "video", "")
		for mp4 in glob.glob(f + pathsep + "*.mp4"):
			moveStorage(mp4, storage + pathsep + "video", "")
		for swf in glob.glob(f + pathsep + "*.swf"):
			moveStorage(swf, storage + pathsep + "video", "")

