#!/usr/bin/env python
__author__ = 'J Dean Brock'

import sys
import zipfile
import os
import re

def try_make_dir(target_dir, default_dir):
    if os.path.isdir(target_dir):
        return target_dir
    elif os.path.exists(target_dir):
        return default_dir
    else:
        try:
            os.mkdir(target_dir)
            return target_dir
        except Exception:
            return default_dir

def unzip_moodle_file(zip_handle, zip_file, zip_target):
    print 'Extracting {0} to {1}'.format(zip_file, zip_target)
    try:
        zip_handle.extract(zip_file, zip_target)
    except Exception as ex:
        raise ex

ZIP_COMPILED = re.compile(
    r"^(\S+)\s+(\S+)_.\d+_assignsubmission_file_(.+)$")

def unzip_main(zip_file):
    arg_match = re.match('^([^-]*)[-](.*)[-]([^-]*[.]zip)$', zip_file)
    target_dir = '.'
    if arg_match is not None:
        target_dir = try_make_dir(arg_match.group(2), '.')
    print 'Extracting files to directory {0}'.format(target_dir)
    try:
        with zipfile.ZipFile(zip_file) as zip_handle:
            for zipped_file in zip_handle.namelist():
                zip_dir = target_dir
                zip_match = ZIP_COMPILED.match(zipped_file)
                if zip_match is not None:
                    student_name = '{1},{0}'.format(
                        zip_match.group(1), zip_match.group(2))
                    student_dir = os.path.join(zip_dir, student_name)
                    zip_dir = try_make_dir(student_dir, zip_dir)
                unzip_moodle_file(zip_handle, zipped_file, zip_dir)
                if zip_match is not None:
                    student_filename = zip_match.group(3)
                    old_file = os.path.join(zip_dir, zipped_file)
                    new_file = os.path.join(zip_dir, student_filename)
                    print '{0} -> {1}'.format(old_file, new_file)
                    os.rename(old_file, new_file)
    except Exception as ex:
        print ex

if __name__ == "__main__":
    if len(sys.argv) == 1:
        sys.exit('No argument given')
    unzip_main(sys.argv[1])
