#!/usr/bin/env python

__author__ = "Artur Duque de Souza"
__author_email__ = "artur.souza@indt.org.br"
__license__ = "GPL"
__version__ = "0.1"

import os
import sys
import pickle
import logging
import lib.utils as utils

from stat import *

__all__ = ("FileList", "list_media_files")


class TranscodedFile(object):
    """This class creates and reads information about transcoded files."""
    opts = {}
    log = logging.getLogger("gms.file_handler")

    def __init__(self, filename, args):
        if filename == "" or not os.path.exists(filename):
            self.opts = args.copy()

            if self.opts["type"][0] != "myth":
                self.opts["original_mtime"] = os.path.getmtime(
                    self.opts["uri"][0])

            name = os.path.basename(self.opts["uri"][0])
            self.opts["original"] = [name]
            output_file = os.path.basename(self.opts["outfile"][0])
            dat_file = output_file + ".dat";
            dat_path = os.path.join (utils.config.get_transcoded_location(),
                dat_file);

            output = open(dat_path, "wb")
            # dumps data using the highest protocol
            pickle.dump(self.opts, output, -1)
            output.close()
        else:
            name = os.path.splitext(os.path.basename(filename))[0]
            dat_file = name + ".dat";
            dat_path = os.path.join (utils.config.get_transcoded_location(),
                dat_file);
            pkl_file = open(dat_path, "rb")
            self.opts = pickle.load(pkl_file)
    # __init__()

# TranscodedFile


class FileList(list):
    """Class to hold file's list - reimplements str and repr."""
    def __str__(self):
        ret = ""
        if len(self) > 0:
            for item in self:
                ret = ret + "%s" % item
        return ret
    # __str__()

    def __repr__(self):
        return self.__str__()
    # __repr__()

# FileList

def list_media_files(directory, file_list):
    """Show all the media files with extension defined in the var 'ext'
    that are in the directory, appending each one to 'file_list'."""
    ext = ['mpg', 'avi', 'mp4', 'nuv', 'mpeg', 'mov']
    for root, dirs, files in os.walk(directory):
        for name in files:
            if os.path.splitext(name)[1].strip(".") in ext:
                dat_file = os.path.join(sys.path[0],root,
                                        os.path.splitext(name)[0]+".dat")

                if name not in file_list and \
                       os.path.exists(dat_file):
                    file_list.append(name)

    return True
# list_media_files()
