#from mod_python import apache

import StyleSheet, formatter
import os, tempfile
import sys, getopt, string


def help_message():
    sys.stdout.write( '''\n\nSwitch: The CSS Preprocessor
Options:
         -h                 displays this help message
         --sss=             SSS or CSS
         --file=            expects an argument
         --python-version   displays Python version
         
         --dir=             Switch will process the entire current directory,
                            and output the result to the directory given as
                            an argument here\n\n''' )
    sys.exit(0)



def parseFile( path ):

    if os.path.isfile( path ):
        
        stylesheet = StyleSheet.SSSStyleSheet( path )
        return stylesheet.cssText
    
    return ''
    
    # stylesheet = StyleSheet.SSSStyleSheet( filename )
    # return stylesheet.cssText


def parse( input ):

	temp_file = tempfile.mkstemp()
	
	sss_file = open( temp_file[1], 'w' )
	
	#print sss_file
	#return ''
		
	sss_file.write( input )
	sss_file.close()
	
	result = parseFile( temp_file[1] )
	
	
	os.remove( temp_file[1] )
	
	return result
	
	
	#temp_file = os.tmpfile()
	#temp_file.write( input )
	#temp_file.close()
	
	#return temp_file.name
	
	#return parseFile( temp_file.name )
	
    #stylesheet = StyleSheet.SSSStyleSheet( )
    #stylesheet.cssText = input
    #return stylesheet.cssText

#
# The following function (handler) will be called from apache when this script
# is assigned as the handler. You do not have to call it explicity
#

def handler(req):

    req.content_type = 'text/css'

    sss_filename = req.filename[0:req.filename.rfind('.css')] + '.sss'

    path_split = os.path.split(sss_filename)

    switch_subdirectory = os.path.join(path_split[0], 'sss')

    result = ''
    
    #first, look for the Switch file
    if os.path.isfile(sss_filename):
        result = parseFile(sss_filename)

    # there's no sss file at this path
    # now we have to check for an 'sss' subdirectory
    # though this is a repeat of the first condition,
    # for readability these conditions have been separated
    elif os.path.exists(switch_subdirectory) and os.path.isfile(os.path.join(switch_subdirectory, path_split[1])):
        result = parseFile(os.path.join(switch_subdirectory, path_split[1]))        

    #ok, we can't find the Switch file anywhere: look for the css file
    elif os.path.isfile(req.filename):
        
        css_file = open(req.filename)
        result = css_file.read()        
        
        
    #can't find the file. return an error
    else:

        return apache.HTTP_NOT_FOUND

    if req.args and 'format=true' in req.args: result = formatter.format(result)
    
    req.write(result)
    return apache.OK


#
# This is where we determine if this is getting called from the command-line 
# or by apache, If we can import mod_python, then this script is getting 
# called from apache.
#
# Right now, options are only available to the command-line invocation, 
# ideally, some would be supported via http request as well (like output 
# formatting).
#

def save_css(destination, filename, sss_file):
    try:
        new_css = open(os.path.join(destination, filename + '.css'), 'w')
        new_css_text = parseFile(sss_file)
        new_css.write(new_css_text)
        new_css.close()
        print '\nFile successfully converted.\n'
    except:
        print "\nCouldn't find the file at:"
        print str(os.path.join(os.getcwd(), filename)) + '\n'
try:
    from mod_python import apache
except:
    try:
        options, xarguments = getopt.getopt(sys.argv[1:], 'h', ['file=', 'sss=', 'python-version', 'dir='])
        for a in options:            
            if a[0] == '-h':
                help_message()
            if a[0] == '--sss':
                print parse(a[1])
            if a[0] == '--file' and a[1] != '':
                file_to_parse = a[1]
                destination = xarguments[0]
                switch_output = parseFile(file_to_parse)
                if destination != '' and os.path.isfile(file_to_parse):
                    file_info = os.path.splitext(file_to_parse)
                    save_css(destination, file_info[0], file_to_parse)
                options.remove(a)
                break
            elif a[0] == '--file' and a[1] == '':
                print '--file expects an argument'
                sys.exit(0)
            if a[0] == '--python-version':
                print 'Python ' + sys.version
                sys.exit(0)
            if a[0] == '--dir':
                print "Destination:\t" + a[1]
                list_dir = os.listdir(os.getcwd())
                for i in list_dir:
                    file_info = os.path.splitext(i)
                    if os.path.isfile(i) and file_info[1] == '.sss':
                        permission = raw_input("Convert?\t" + i + '\n(yes/no) ')
                        permission = permission.lower()

                        if permission in ('y', 'yes') and os.path.isdir(a[1]):
                            save_css(a[1], file_info[0], i)
                        else:
                            print 'Skipping ' + i + '\n'

                        
    except getopt.error:
        print 'Error: You tried to use an unknown option or the argument for an option that requires it was missing. Try \'options.py -h\' for more information.'
        sys.exit(0)
