#!/usr/bin/env python
"""
Move a document to the correct documents folder
"""

import filecmp
import os
import re
import shutil
import sys

from datetime import date

_slugify_strip_re = re.compile(r'[^\w\s-]')
_slugify_hyphenate_re = re.compile(r'[-\s]+')
def slugify(value):
    """
    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.

    From Django's "django/template/defaultfilters.py".
    """
    import unicodedata
    if not isinstance(value, unicode):
        value = unicode(value)
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
    value = unicode(_slugify_strip_re.sub('', value).strip().lower())
    return _slugify_hyphenate_re.sub('-', value)

def usage():
    return "Usage: mv-to-docs [SRC_DOC] [CATEGORY] [MSG]"

if __name__ == "__main__":
    try:
        file_name = sys.argv[1]
        dir_name = slugify(sys.argv[2])
    except IndexError:
        sys.exit(usage())

    try:
        msg = slugify(sys.argv[3])
    except IndexError:
        msg = ""

    file_type = file_name.split(".")[-1]

    if not os.path.isfile(file_name):
        print "ERROR: Cannot find file '%s'" % file_name
        sys.exit(usage())

    file_date = date.fromtimestamp(os.path.getmtime(file_name))

    doc_path = os.path.expanduser("~/documents/records/%s" % dir_name)
    if not os.path.exists(doc_path):
        print "Could not find path, creating directory '%s'" % doc_path
        os.mkdir(doc_path)

    path_with_year = "%s/%s" % (doc_path, file_date.strftime("%Y"))
    if not os.path.exists(path_with_year):
        os.mkdir(path_with_year)
        pass

    new_file_path = "%s/%s_%s.%s" % \
        (path_with_year, file_date.strftime("%Y-%m-%d"), msg, file_type)

    if not os.path.isfile(new_file_path):
        print "Moving file '%s' to '%s'" % (file_name, new_file_path)
        shutil.copyfile(file_name, new_file_path)
        os.unlink(file_name)
    else:
        if filecmp.cmp(new_file_path, file_name):
            print "Two files already exist and are same: '%s' and '%s'" % \
                (file_name, new_file_path)
        else:
            print "Destination file '%s' already exists" % (new_file_path)