#!/usr/bin/env python
# encoding: utf-8
'''
OSUtils -- shortdesc

OSUtils is a description

It defines classes_and_methods

@author:     user_name
            
@copyright:  2013 organization_name. All rights reserved.
            
@license:    license

@contact:    user_email
@deffield    updated: Updated
'''

import sys
import os
import re
from tempfile import mkstemp
from shutil import move
from optparse import OptionParser

__all__ = []
__version__ = 0.1
__date__ = '2013-10-29'
__updated__ = '2013-10-29'

DEBUG = 1
TESTRUN = 0
PROFILE = 0
class DirectoryWalker(object):
    # MAX_FILENAME_LENGTH  based on http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx 
    MAX_FILENAME_LENGTH = 260
    
    def __init__(self, overrideMaxLen = True):
        self.overrideMaxLen = overrideMaxLen
        self.continueWalking = True

        
    def scanDirectory(self, directory, dirMethod, **kwargs):
        directory = os.path.abspath(directory)
        for file in [file for file in os.listdir(directory) if not file in [".",".."]]:
            nfile = os.path.join(directory,file)            
            if os.path.isdir(nfile):
                dirMethod(nfile, **kwargs)
                self.scanDirectory(nfile,dirMethod, **kwargs)

            
    def walk(self, dir, method):
        dir = os.path.abspath(dir)
        for file in [file for file in os.listdir(dir) if not file in [".",".."]]:
            nfile = os.path.join(dir,file)            
            if os.path.isdir(nfile):
                self.walk(nfile,method)
            else:
                method(nfile)
                
class AssemblyInfoFinder(DirectoryWalker):
    assembly_info_list = []
    
    def __init__(self, overrideMaxLen = True):
        DirectoryWalker.__init__(self, overrideMaxLen)
        self.assembly_info_list = []
        
    def find(self, directory):
        self.walk(directory, self.verify)
    
    def verify(self, file_path):
        head, tail = os.path.split(file_path)
        if tail == "AssemblyInfo.vb":
            self.assembly_info_list.append(file_path)
    
        
    
                
def prt(nfile):
    head, tail = os.path.split(nfile)
    if tail == "AssemblyInfo.vb":
        print nfile
        f = open(nfile, 'r')
        for line in f:
            matchObj = re.match(r'<Assembly: AssemblyTitle\("(\w*)"\)>', line, re.M|re.I)
            if matchObj:
                print "\tAplicacion: ", matchObj.group(1)
            matchObj = None
            matchObj = re.match(r'<Assembly:\sAssemblyFileVersion\("(\d\.\d\.(\d|\*)\.?\d?)"\)>', line, re.M|re.I)
            if matchObj:
                print "\tVersión: ", matchObj.group(1)
                #update_version(nfile)
        f.close()

def update_version(file_path, version="1.2.5"):
    #os.remove(file_path)
    fh, abs_path = mkstemp()
    print abs_path
    new_file = open(abs_path, 'w')
    with open(file_path, 'rb') as old_file: 
        for line in old_file:
            matchObj = re.match(r'<Assembly:\sAssemblyFileVersion\("(\d\.\d\.(\d|\*)\.?\d?)"\)>', line, re.M|re.I)
            if matchObj:
                new_file.write(r'<Assembly: AssemblyFileVersion("' +version +'")>\n')
            else:
                new_file.write(line.rstrip('\r\n'))
                new_file.write('\n')
        #old_file.close()
        #print "Status", old_file.closed()
    new_file.close()
    os.close(fh)    
    os.remove(file_path)
    move(abs_path, file_path)
    print "Finished ", file_path
        
            
                       
def main(argv=None):
    '''Command line options.'''
    #directory_to_scan =r'C:\Users\lberrocal\Documents\Visual Studio 2010\Projects\booking_web_page'
    directory_to_scan =r'C:\Users\lberrocal\Documents\Visual Studio 2010\Projects\vessel_scheling_app'
    #dw = DirectoryWalker()
    #dw.walk(directory_to_scan, prt)
    af = AssemblyInfoFinder()
    af.find(directory_to_scan)
    for ainfo in af.assembly_info_list:
        #update_version(ainfo)
        prt(ainfo) 
    
    program_name = os.path.basename(sys.argv[0])
    program_version = "v0.1"
    program_build_date = "%s" % __updated__
 
    program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
    #program_usage = '''usage: spam two eggs''' # optional - will be autogenerated by optparse
    program_longdesc = '''''' # optional - give further explanation about what the program does
    program_license = "Copyright 2013 user_name (organization_name)                                            \
                Licensed under the Apache License 2.0\nhttp://www.apache.org/licenses/LICENSE-2.0"
 
    if argv is None:
        argv = sys.argv[1:]
    try:
        # setup option parser
        parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
        parser.add_option("-i", "--in", dest="infile", help="set input path [default: %default]", metavar="FILE")
        parser.add_option("-o", "--out", dest="outfile", help="set output path [default: %default]", metavar="FILE")
        parser.add_option("-v", "--verbose", dest="verbose", action="count", help="set verbosity level [default: %default]")
        
        # set defaults
        parser.set_defaults(outfile="./out.txt", infile="./in.txt")
        
        # process options
        (opts, args) = parser.parse_args(argv)
        
        if opts.verbose > 0:
            print("verbosity level = %d" % opts.verbose)
        if opts.infile:
            print("infile = %s" % opts.infile)
        if opts.outfile:
            print("outfile = %s" % opts.outfile)
            
        # MAIN BODY #
        
    except Exception, e:
        indent = len(program_name) * " "
        sys.stderr.write(program_name + ": " + repr(e) + "\n")
        sys.stderr.write(indent + "  for help use --help")
        return 2


if __name__ == "__main__":
    if DEBUG:
        sys.argv.append("-h")
    if TESTRUN:
        import doctest
        doctest.testmod()
    if PROFILE:
        import cProfile
        import pstats
        profile_filename = 'OSUtils_profile.txt'
        cProfile.run('main()', profile_filename)
        statsfile = open("profile_stats.txt", "wb")
        p = pstats.Stats(profile_filename, stream=statsfile)
        stats = p.strip_dirs().sort_stats('cumulative')
        stats.print_stats()
        statsfile.close()
        sys.exit(0)
    sys.exit(main())