#start_radsunpath.rb 
#Author: Marija Velickovic, maricanis@deluminalab.com
#Copyright De Luminae, June 2009.
#
#Description: This plug-in starts external program RadSunpath. Then it imports su2rad.rb output into the program if exists.
#----------------------
#
# modified 30/08/09 by Thomas Bleicher


require 'sketchup.rb'

## load SU2RAD before RadSunpath
begin
    require 'su2rad.rb'
rescue NameError
    printf "SU2RAD is not installed on this machine. - No export possible!\n"
end


module RadSunpath

    def RadSunpath.findProgramPath
        ## find RadSunpath executable:
        ## - Check few standard paths
        ## - Check if Windows registry contains executable path
        rpath = "\\RadSunpath\\radsunpath.exe"
        progs = []
        progs.push(Sketchup.read_default("RadSunpath", "executable",""))
        if ENV.has_key?("ProgramFiles")
            ## localised "Program Files" folder
            progs.push(ENV['ProgramFiles'] + rpath)
        end
        progs.push("C:\\Program Files" + rpath)
        progs.push("C:" + rpath)
        ## RadSunpath program path in Windows registry file
        progs.each { |prog|
            if File.exists?(prog)
                RadSunpath.setProgramPath(prog)
                return prog
            end
        }
        ## return nil to signal failure
        printf "RadSunpath: program path not found!\n"
        @programPath = nil
    end
        
    def RadSunpath.getProgramPath
        ## return (existing!) path to RadSunpath.exe
        ## value is used in SU2RAD to show and start RadSunpath option
        if @programPath and not File.exists?(@programPath)
            printf "[W] Warning: path #{@programPath} does not exists."
            @programPath = nil
        end
        return @programPath
    end
    
    def RadSunpath.getProjectDirectory
        ## find path of latest export via Su2Rad module
        begin
            if Su2Rad
                printf "found Su2Rad module\n"
                path = Su2Rad.getLatestExportPath()
            end
            if not path or not FileTest.directory?(path)
                ans = UI.messagebox("Radiance project directory '#{path}' doesn't exist.\nRadSunpath program will start with empty project.", MB_OKCANCEL, "Start RadSunpath")
                if ans != 1
                    return "cancel"
                end
                return ""
            end
            return path
        rescue NameError
            ## module Su2Rad does not exist yet - August '09
            ## => access string attribute directly
            return RadSunpath.read_directory()
        end
    end
    
    def RadSunpath.read_directory
        ## find su2rad project directory for the current skp model
        ## function is kept to allow migration to Su2Rad module
        printf "[W] Warning: use of RadSunpath.read_directory is deprecated.\n"
        project_directory = ""
        optsString = Sketchup.active_model.get_attribute('SU2RAD', 'EXPORTOPTIONS')
        if optsString == nil
            ## no attribute found
            ans = UI.messagebox("Sketchup plugin 'su2rad' not installed or not used in current project.\nPlease install su2rad and export project to Radiance\nto be able to import it in RadSunpath.\nRadSunpath will start with empty project", MB_OKCANCEL, "Start RadSunpath")
            if ans != 1
                return "cancel"
            end
            return ""
        else
            ## evaluate attribute
            project_directory = RadSunpath.setOptionsFromString(optsString)
            printf "RadSunpath: found export path in attributes: '%s'\n" % project_directory	
            if FileTest.directory?(project_directory)
               printf " => project directory exists.\n"
               return project_directory
            else
               printf " => project directory does not exist!\n"
               ans = UI.messagebox("Radiance project directory '#{project_directory}' doesn't exist.\nRadSunpath program will start with empty project.", MB_OKCANCEL,"Start RadSunpath")
               if ans != 1
                   return "cancel"
               end
               return ""
            end
        end
        ## failsave: return empty string
        printf "[W] Warning:\n    RadSunpath.read_directory() failsave: returning '#{project_directory}'.\n"
        return project_directory
    end

    def RadSunpath.runSystemCmd(cmd)
        ## execute external command 'cmd'	
        if RUBY_PLATFORM =~ /mswin/i
            cmd.gsub!(/\//, '\\')
        else
            cmd.gsub!(/\\/, '/')
        end
        printf "system cmd= %s\n" % cmd
        result = system(cmd)
        printf "result= %s\n" % result
        if result == true
            printf "System cmd '#{cmd}' started\n"
        else
            ## could be improved with error code or message
            UI.messagebox("System cmd '#{cmd}' can not be started.\nResult: #{result}", MB_OK, "Start RadSunpath")
        end
    end

    def RadSunpath.selectProgramPath
        prog = UI.openpanel("RadSunpath executable", "", "*.exe")
        if prog == nil
            ## dialog canceled
            return
        end
        if File.exists?(prog)
            RadSunpath.setProgramPath(prog)
            UI.messagebox("RadSunpath.programPath successfully set to\n'#{prog}'.", MB_OK, "Program path set.")
        else
            UI.messagebox("path '#{prog}' does not exists.\nProgramPath was not set!", MB_OK, "Program path not set.") 
        end
    end
    
    def RadSunpath.setOptionsFromString( params)
        ## extract 'scenePath' option value from the options string read from skp file
        ## set export options from string <p>
        pairs = params.split("&")
        pairs.each { |pair|
            k,v = pair.split("=")
            #printf k
            if k == "scenePath"
                return v
            end
        }
        return ""
    end 

    def RadSunpath.setProgramPath(path)
        if not File.exists?(path)
            ## reset @programPath as flag for menu validation
            @programPath = nil
            return
        end
        path.gsub!(/\\/, '/')
        if RUBY_PLATFORM =~ /mswin/i
            ## write path only to Windows registry
            Sketchup.write_default("RadSunpath", "executable", path)
        end
        @programPath = path
        printf "RadSunpath: program path set to '#{path}'\n"
    end
    
    def RadSunpath.start_rsp(project_directory="")
        ## main function called from SketchUp menu (arg="") or Su2Rad (arg=scenedir)
        if RadSunpath.getProgramPath == nil
            UI.messagebox("RadSunpath not found!\nInstall RadSunpath program before plug-in execution.", MB_OK, "RadSunpath not found ...")
            return
        end
        
        ## if project_directory not set try to find it
        if project_directory == ""
            project_directory = RadSunpath.getProjectDirectory()
        end
        if project_directory == "cancel"
            ## dialog canceled by user
            return
        end
        
        ## user chose to start with empty project
        prog = RadSunpath.getProgramPath()
        if project_directory == ""
            cmd = "\"#{prog}\""
        else
            cmd = "\"#{prog}\" \"#{project_directory}\""
        end
        thread_tmp = Thread.new{ RadSunpath.runSystemCmd(cmd) }
    end 
    
    def RadSunpath.validateMenu
        if RadSunpath.getProgramPath() == nil
            #printf "validateMenu: MF_GRAYED\n"
            return MF_GRAYED
        else
            #printf "validateMenu: MF_ENABLED\n"
            return MF_ENABLED
        end
    end
    
    ## call findProgramPath to create @programPath variable
    RadSunpath.findProgramPath()
    
end # end module RadSunpath


#-----------------------
# Add an 'Start Radsunpath program' command to Plugins menu
if ( not file_loaded?("start_radsunpath.rb") )
    printf "adding menu 'RadSunpath'\n"
    rsmenu = UI.menu("Plugins").add_submenu("RadSunpath")
    printf " => adding item 'Set program path'\n"
    rsmenu.add_item( $exStrings.GetString("Set program path") ) { RadSunpath.selectProgramPath }
    printf " => adding item 'Start program'\n"
    rsstart = rsmenu.add_item( $exStrings.GetString("Start program") ) { RadSunpath.start_rsp }
    printf " => adding validator ...\n"
    rsmenu.set_validation_proc(rsstart) { RadSunpath.validateMenu }
    printf " => done.\n"
    ## test entry
    rsmenu.add_item( $exStrings.GetString("TEST getProjectDirectory") ) { RadSunpath.getProjectDirectory }
end
#------------------
file_loaded("start_radsunpath.rb")

