#!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0

# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/

# Problem description:
# https://developers.google.com/edu/python/exercises/copy-special


import sys
import re
import os
import shutil
import subprocess
import zipfile

"""Copy Special exercise

"""


def is_special(name):
    if re.search(r"__.*__", name):
        print(name + ' is special')
        return True
    print(name + ' not special')
    return False


def get_special_paths(d):
    special = []

    for f in os.listdir(d):
        file_to_check = d + '/' + f
        if os.path.isfile(file_to_check) and is_special(f):
            special.append(file_to_check)
    return special


def copy_to_dir(paths, dest_dir):
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)

    for path in paths:
        filename = path.split('/')[-1]
        shutil.copyfile(path, dest_dir + '/' + filename)
    pass


def copy_to_zip(paths, zip_fname):
    with zipfile.ZipFile(zip_fname, 'w') as myzip:
        for p in paths:
            myzip.write(p)
    pass


def main():
    # This basic command line argument parsing code is provided.
    # Add code to call your functions below.

    # Make a list of command line arguments, omitting the [0] element
    # which is the script itself.
    args = sys.argv[1:]
    if not args:
        print("usage: [--todir dir][--tozip zipfile] dir [dir ...]")
        sys.exit(1)

    # todir and tozip are either set from command line
    # or left as the empty string.
    # The args array is left just containing the dirs.
    todir = ''
    if args[0] == '--todir':
        todir = args[1]
        del args[0:2]

    tozip = ''
    if args[0] == '--tozip':
        tozip = args[1]
        del args[0:2]

    if len(args) == 0:
        print("error: must specify one or more dirs")
        sys.exit(1)

    #check each directory given in the input
    special_paths = []
    for d in args:
        print('processing ' + d)
        special_paths.extend(get_special_paths(d))

    if todir:
        copy_to_dir(special_paths, todir)

    if tozip:
        copy_to_zip(special_paths, tozip)

if __name__ == "__main__":
    main()
