require 'mccloud/util/iterator'

module Mccloud
  module Command
    def package(selection=nil,options=nil)

      if selection.nil?
        puts "[Error] We need at least a name of a machine."
        exit
      end


      #f=Fog::Compute.new({ :region => "eu-west-1", :provider => "AWS"})
      # i=f.create_image("i-c1ac2bb7","name","description")
      # f.images.all({ "Owner" => "self"})
      # f.deregister_image("ami-796d5b0d")

      on_selected_machines(selection) do |id,vm|

        time=Time.new
        strtime=time.strftime("%Y-%m-%d-%H-%M-%S")
        name=""

        if options["name"].nil?
          name="#{vm.name}-#{strtime}"
        else
          name=options["name"]
        end

        description=""
        if options["description"].nil?
          description="Autogenerated snapshot from machine #{vm.name}"
        else
          description=options["description"]
        end

        filter=@environment.config.mccloud.filter
        fullname="#{@environment.config.mccloud.filter}#{name}"

        provider= @environment.config.providers[vm.provider]
        begin
          result=provider.create_image(id,name,description)
          imageId=result.body["imageId"]
          puts "[#{vm.name}] image #{imageId} with #{description} being created"

          unless options["dontwait"]
            sleep 3
            counter=0
            max_tries=5
            #Pending
            state="pending"
            until state!="pending" do
              print "."
              sleep 2
              image=provider.images.get(imageId)

              if image.nil?
                sleep 3
                print "."
              else
                state=image.state
              end
            end
            puts ""
            puts "[#{vm.name}] creation done!"
          end
        rescue Fog::Service::Error => fogerror
          puts "[Error] #{fogerror}"

        end
        #      vm.instance.start
      end
    end
  end
end
