module Devops
  module Model
    class CategoryProvider
      attr_accessor :name, :account, :type, :connector

      SERVER_TYPE = "server"
      STACK_TYPE = "stack"

      def initialize hash
        self.name = hash["name"]
        self.account = hash["account"]
        self.type = hash["type"]
      end

      def to_hash
        {
          "name" => self.name,
          "account" => self.account,
          "type" => self.type
        }
      end

      def provider_instance
        @provider_instance ||= ::Provider.get_connector(self.name, self.account)
      end

      def validate_provider_params
        unless ::Provider.providers.include?(self.name)
          raise Devops::Exception::ValidationError.new nil, {"name" => "Invalid provider"}
        end
        types = [SERVER_TYPE, STACK_TYPE]
        unless types.include?(self.type)
          raise Devops::Exception::ValidationError.new nil, {"type" => "Invalid type, available values: #{types.joint(', ')}"}
        end
        provider_instance
      rescue Devops::Exception::RecordNotFound
        raise Devops::Exception::ValidationError.new nil, {"account" => "Invalid account. Account not found"}
      end

    end
  end
end

