#!/usr/bin/env python

import os
import sys
import imp
import re
import glob
import argparse
from argparse import RawTextHelpFormatter
from media_transporter.classes import TransportException, Storage, TvFile, MovieFile

flatten_list = lambda l: [item for sublist in l for item in sublist]
"""lambda: lambda function to flatten a list of nested lists to a single list."""

if __name__ == '__main__':
    parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description="""media-transporter serves to make the tedious process of extracting and moving downloaded TV shows and Movies to their final destination easier and automated. Works best with applications like Otomatic and Transmission. media-transport requires a configuration file to be used. Refer to the example config.py here:\n\nhttps://raw.githubusercontent.com/stevecoward/media-transporter/master/media_transporter/config_example.py""")
    parser.add_argument('-c', '--config', metavar='config path', type=str, required=True, help='Absolute path to media-transporter config file.')
    args = parser.parse_args()

    config = None
    if os.path.exists(args.config):
        config = imp.load_source('config', args.config)
    else:
        print 'Path to config file was not found. Please check the path and try again.'
        sys.exit(1)

    download_path = os.path.expanduser(config.download_path)
    os.chdir(download_path)

    storage = Storage(config)
    if storage.capacity_reached():
        raise TransportException(
            '[!] Media share capacity reached, exiting...', True)

    categorized_files = {
        'tv': [],
        'movie': [],
    }

    """Gather any media files and folders within the user-specified download directory."""
    files_to_check = []
    files_to_check.extend(flatten_list(
        [glob.glob(extension) for extension in ['*.mkv', '*.avi', '*.mp4', '*.mov']]))
    files_to_check.extend(filter(os.path.isdir, os.listdir(download_path)))

    """Sort files and folders into tv or movie categories.

    Store the file path and any regex-matched information for later use."""
    for file in files_to_check:
        regex_tv = re.compile(r'%s' % config.regex_tv)
        regex_movie = re.compile(r'%s' % config.regex_movie)

        if regex_tv.findall(file):
            categorized_files['tv'].append({
                'path': file,
                'info': regex_tv.search(file).groups()
            })
        elif regex_movie.findall(file):
            categorized_files['movie'].append({
                'path': file,
                'info': regex_movie.search(file).groups()
            })

    """Loop through and process TV and Movie files."""
    for media_type, files in categorized_files.iteritems():
        if media_type == 'tv':
            for file_info in files:
                tv_obj = TvFile(config, download_path, file_info.get(
                    'path'), file_info.get('info'))
                tv_obj.prepare_destination()
                tv_obj.process()
        elif media_type == 'movie':
            for file_info in files:
                movie_obj = MovieFile(config, download_path, file_info.get(
                    'path'), file_info.get('info'))
                movie_obj.prepare_destination()
                movie_obj.process()
