module JF
   module MeshImporter

      unless @menu_id
         @menu_id = UI.menu("Extensions").add_item("Mesh Importer") { JF::MeshImporter.main() }
      end

      def self.msg(m)
         if SKETCHUP_CONSOLE.visible?
            puts m
         else
            UI.messagebox(m)
         end
      end

      def self.file_select
         UI.openpanel("Select Mesh File:", "", "Mesh Files|*.stl?;*.ply?|STL Files Only|*.stl?|PLY Files Only|*.ply?;|Any File|*.*||")
      end

      def self.convert(path)
         if Sketchup.platform == :platform_win
            a2s = File.dirname(__FILE__) + "/win/a2s.exe"
            result = %x["#{a2s}" "#{path}"]
            puts("Mesh Importer Result:\n#{result}")

            logfile = path + ".log"
            if File.exists?(logfile)
               puts "Mesh Importer Log:"
               puts File.read(logfile)
            end
         else
            # 
         end
      end

      def self.main

         filename = file_select()
         return if filename.nil?

         convert(filename)

         file_to_import = filename + ".skp"

         if File.exists?(file_to_import)
            Sketchup.active_model.start_operation("Mesh Import", true)
            cdef = Sketchup.active_model.definitions.load(file_to_import)
            Sketchup.active_model.entities.add_instance(cdef, IDENTITY)
            Sketchup.send_action("viewZoomExtents:")
            Sketchup.active_model.commit_operation
         else
            puts "#{file_to_import} was not created."
         end

      end # main

   end
end

