require "fog"
require_relative "category_provider"
require_relative "category_cloud_provider"

module Provider

  @@providers = {}

  def self.register _class
    provider = _class.instance
    @@providers[_class::PROVIDER] = provider
    DevopsLogger.logger.info("Added provider: " + _class::PROVIDER)

    provider.accounts.each do |account|
      provider.create_connector DevopsConfig.config, account
      DevopsLogger.logger.info("Connector for provider '#{_class::PROVIDER}' and account '#{account.account_name}' has been initialized")
    end
  end

  def self.providers
    @@providers.keys
  end

  def self.provider provider_name
    provider = @@providers[provider_name]
    raise Devops::Exception::RecordNotFound.new "Provider with name '#{provider_name}' not found" if provider.nil?
    provider
  end

  def self.all
    @@providers.values
  end

  def self.get_connector provider_name, account
    Provider.provider(provider_name).connector(account)
  end

  def self.create_category_provider hash
    Provider.provider(hash["name"]).create_category_provider(hash)
  end

  class AbstractProvider

    include Singleton

    @@account_class
    def self.account_class pname, _class
      @@account_class = _class
      @@account_class.all.each do |account|
        @@providers[pname].create_connector DevopsConfig.config, account
        DevopsLogger.logger.info("Connector for provider '#{pname}' and account '#{account.account_name}' has been initialized")
      end
    end

    def connectors
      @connectors ||= {}
    end

    def connector account_name
      con = connectors[account_name]
      raise Devops::Exception::RecordNotFound.new "Account with name '#{account_name}' not found" if con.nil?
      con
    end

    def add_connector account_name, conn
      connectors[account_name] = conn
    end

    def delete_connector account_name
      connectors.delete(account_name)
    end

    def create_connector config, account
      raise "override me"
    end

    def create_account hash
      raise "override me"
    end

    def create_category_provider hash
      raise "override me"
    end

    def accounts
      @@account_class.all
    end

  end
end
