require_relative 'category_provider'
require "commands/image"

module Devops
  module Model
    class CategoryCloudProvider < CategoryProvider

      include ::ImageCommands
      include ActiveModel::Validations

      attr_accessor :flavor, :image, :security_groups

      validate :validate_cloud_params

      def initialize d={}
        super(d)
        self.flavor = d["flavor"]
        self.image = d["image"]
#          b = d["security_groups"] || ["default"]
        self.security_groups = d["security_groups"]
      end

      def to_hash
        h = super
        h.merge!({
          "flavor" => self.flavor,
          "image" => self.image,
          "security_groups" => self.security_groups
        })
      end

      def validate_flavor
        if flavor.nil?
          errors.add(:flavor, "'flavor' is udefined")
        else
          if provider_instance.flavors.detect{|f| f['id'] == flavor}.nil?
            errors.add(:flavor, "'flavor' is invalid")
          end
        end
      end

      def validate_image
        if image.nil?
          errors.add(:image, "'image' is udefined")
        else
          if get_available_provider_images(self.provider, self.provider_account).detect{|i| i["id"] == @model.image}.nil?
            errors.add(:image, "'image' is invalid")
          end
        end
      end

      def waiting_server(server, out)
        out << "\nWaiting for a server"
        out.flush
        provider_instance.waiting_server(server, out)
      end

    end
  end
end

