#!/usr/bin/python
import sys, os
from optparse import OptionParser

from easy_extract import VERSION
from easy_extract.archives.xtm import XtmArchive
from easy_extract.archives.rar import RarArchive
from easy_extract.archives.hj_split import HJSplitArchive
from easy_extract.archives.seven_zip import SevenZipArchive
from easy_extract.archive_finder import ArchiveFinder

class EasyExtract(ArchiveFinder):
    """User interface for extracting archives"""

    def __init__(self, paths, recursive=False,
                 force_extract=False, repair=True, clean=False):
        self.excludes = []
        self.clean = clean
        self.repair = repair
        self.force_extract = force_extract

        super(EasyExtract, self).__init__(paths, recursive,
                                          [RarArchive, SevenZipArchive,
                                           XtmArchive, HJSplitArchive,])

        if self.can_extract(self.force_extract):
            self.extract_archives(self.repair, self.clean)
        else:
            print 'Nothing to do !'

    def get_path_archives(self, path, filenames, archive_classes):
        print 'Scanning %s...' % os.path.abspath(path)
        archives = super(EasyExtract, self).get_path_archives(
              path, filenames, archive_classes)
        return archives

    def can_extract(self, force):
        if self.archives:
            if force: return True
            for archive in self.archives:
                print archive

            extract = raw_input('%i archives found. Extract all ? [Y]es / No / Select : ' % len(self.archives))
            if not extract or 'y' in extract.lower():
                return True
            if 's' in extract.lower():
                for archive in self.archives:
                    extract = raw_input('Extract %s ? [Y]es / No : ' % archive)
                    if extract and not 'y' in extract.lower():
                        self.excludes.append(archive)
                return bool(self.archives)
        return False

    def extract_archives(self, repair, clean):
        for archive in self.archives:
            if archive not in self.excludes:
                success = archive.extract(repair)
                if success and clean:
                    archive.remove()

if __name__ == '__main__':
    parser = OptionParser(usage='Usage: %prog [options] [directory]...',
                          version='%prog ' + VERSION)
    parser.add_option('-f', '--force', dest='force_extract', action='store_true',
                      help='Do not prompt confirmation message', default=False)
    parser.add_option('-n', '--not-repair', dest='repair', action='store_false',
                      help='Do not try to repair archives on errors', default=True)
    parser.add_option('-r', '--recursive', dest='recursive', action='store_true',
                      help='Find archives recursively', default=False)
    #parser.add_option('-c', '--clean', dest='clean', action='store_true',
    #                  help='Remove archives files successfully extracted', default=False)

    (options, args) = parser.parse_args()

    directories = ['.']
    if len(args):
        directories = args

    print '--** Easy Extract v%s **--' % VERSION
    EasyExtract(directories, options.recursive,
                options.force_extract, options.repair)#,
                #options.clean)
