require 'exceptions/parser_error'
module Devops
  module Model
    module ModelWithProviderAccount

      class << self
        def included(mod)
          mod.field :provider, type: String
          mod.field :provider_account, type: String

          mod.validates_presence_of :provider, message: "'provider' is undefined"
          mod.validates_presence_of :provider_account, message: "'provider_account' is undefined"
        end
      end

      def check_provider_account_type hash
        raise Devops::Exception::ParserError.new("Parameter 'provider' is not a string") unless hash["provider"].is_a?(String)
        raise Devops::Exception::ParserError.new("Parameter 'provider_account' is not a string") unless hash["provider_account"].is_a?(String)
      end

      def validate_provider
        providers = ::Provider.providers
        unless providers.include?(self.provider)
          errors.add(:provider, "Invalid provider, available values: '#{providers.join("', '")}'")
          return
        end
        begin
          #factory = ::Provider::ProviderFactory.get_accounts_factory self.provider
          #Devops::Exception::RecordNotFound.new if factory.nil?
          provider_instance
        rescue Devops::Exception::RecordNotFound
          puts "not f inst"
          errors.add(:provider_account, "Provider account '#{self.provider_account}' does not exist")
        end
      end

      def provider_instance
        @provider_instance ||= ::Provider.get_connector(self.provider, self.provider_account)
      end

      def provider_hash
        {
          "provider" => self.provider,
          "provider_account" => self.provider_account
        }
      end

    end
  end
end

