require 'rubygems'
require 'rest_client'
require 'zip'
require 'zip/zipfilesystem'
require 'open-uri'

module Factor
  module Client
    class Client
      HOST = "http://localhost:3000"
    
      def register(email,password)
      end
    
      def login(email, password)
      end
    
      def login_token(token)
        @token=token
      end
    
      def load_workflows(engine)
        workflows = rest_get("workflows")
        workflows.each do |workflow|
          workflow_definition = JSON.parse(workflow['definition'])
          workflow=Factor::Workflow.new(workflow_definition)
          engine.load_workflow(workflow)
        end
        engine
      end
    
      def load_credentials(engine)
      
        credentials_definition = rest_get("credentials")
        credentials = JSON.parse(credentials_definition["bag"])
        engine.load_credentials(credentials)
      
        engine
      end
    
    
      def load_channels(engine)
      
        # get list of channels
        channels = rest_get("channels")
      
        #load each channel
        channels.each do |channel|
        
          # URI of the zip file containing the module
          uri = URI.parse(channel['zip_url'])
        
          # temp file to store the zip for download
          temp_file = Tempfile.new([uri.to_s.gsub(/\W+/,'-'), '.zip'], :encoding => 'ascii-8bit')
        
          # temp directory where zip will be decompressed
          unzip_dir=temp_file.path[0..-5]
        
          # download
          open(uri.to_s,"rb") do |bin|
            temp_file.print bin.read
          end
          temp_file.close
        
          # unzip download zip into unzipped directory
          unzip(temp_file.path,unzip_dir)
        
          Dir.glob("#{unzip_dir}/#{channel['name'].downcase}/*.rb").each do |file|
            engine.load_channel(file)
          end
        
        end
      
      
        engine
      end
    
    
      private
    
      def fix_github_zip_archive(file)
        Zip::ZipFile.open(file.path) do |zip|
          basedir = zip.entries.first.name
          zip.remove zip.entries.first
          zip.each do |entry|
            target = entry.name.sub(/^#{basedir}/,'')
            if entry.directory?
              zip.dir.mkdir(target)
            else
              zip.file.open(entry.name) do |istream|
                zip.file.open(target, 'w') do |ostream|
                  ostream.write istream.read
                end
              end
            end
            zip.remove entry
          end
        end
      end
    
      def unzip(zip, unzip_dir, remove_after = false)
        Zip::ZipFile.open(zip) do |zip_file|
          zip_file.each do |f|
            f_path=File.join(unzip_dir, f.name)
            FileUtils.mkdir_p(File.dirname(f_path))
            zip_file.extract(f, f_path) unless File.exist?(f_path)
          end
        end
        FileUtils.rm(zip) if remove_after
      end
    
      def rest_get(path)
        JSON.parse(RestClient.get "#{HOST}/#{path}.json?auth_token=#{@token}")
      end
    
    end
  end
end