#!/usr/bin/python
'''The primary fyp loading file'''

from __future__ import print_function #for using print as a function rather than a statement

from optparse import OptionParser #option parsing
from zipfile import ZipFile, BadZipfile #the extractor and related exceptions
from tempfile import mkstemp as make_temp_file, mkdtemp as make_temp_dir #the temporary file/dir creators
from webbrowser import open_new as launch_browser #the html viewer
from sys import stderr #so we can print to stderr
from os import remove, removedirs, walk #for removing the temporary files/dirs, walking them
from os.path import isfile, join #ensure we're dealing with an actual file, system paths

class FypLoader:
    '''A class that loads and displays a fyp file'''

    def __init__(self, filename):
        '''Initialize the class'''
        if isfile(filename):
            try:
                with open(filename) as f:
                    self.extract_file(f)
            except IOError:
                message = 'The file "{}" could not be found.'.format(filename)
                print(message, file=stderr)
        else:
            message = '"{}" is not a file.'.format(filename)
            print(message, file=stderr)

    def extract_file(self, fypFile):
        '''extract the archive into a temporary location'''
        try:
            with ZipFile(fypFile, 'r') as zipFile:
                tmpDir = make_temp_dir()
                print(tmpDir) #for debugging purposes, printing this to stdout at the moment
                zipFile.extractall(tmpDir)
                indexPath = self.find_index_file(tmpDir)
                launch_browser(tmpDir +'index.html')
        except BadZipfile: #TODO: inherit this exception type, make BadFypfile
            print('"{}" is a bad file.'.format(fypFile.name), file=stderr)
            
    def find_index_file(self, tmpDir):
        '''find the highest level index file within in the temporary directory'''
        indexPath = ""
        for currentpath, dirnames, filenames in walk(tmpDir):
            try:
                indexPath = filenames[filenames.index('index.html')]
                continue
            except ValueError:
                ''''''
                #try again, deeper
        if indexPath == "":
            raise BadZipfile()
        return indexPath

if __name__ == "__main__":
    '''Extracts the fyp file into a temporary directory,
    then opens a browser window to view the fyp file'''

    parser = OptionParser()
    (options, args) = parser.parse_args()
    
    try:
        filename = args[0]
    except IndexError as e:
        message = 'At least one argument is required.'
        print(message, file=stderr);

    FypLoader(filename)
