require_relative 'chef_node_name_builder'
require 'providers/aws/aws_connector'
class Devops::Executor::StackExecutor
  class StackServersPersister
    attr_reader :stack

    def initialize(stack)
      @stack = stack
      @project = Devops::Model::Project.find(stack.project)
      @deploy_env = @project.environment(stack.environment)
      @category = @deploy_env.get_category(stack.category)
    end

    def persist(provider_info)
      name = server_name_from_info(provider_info)

      server_attrs = {
        '_id' => provider_info['id'],
        'name' => name,
        'cm_name' => name,
        'created_by' => stack.owner,
        'environment' => @deploy_env.id,
        'category' => @category.id,
        'ssh_key' => provider_info['key_name'] || @stack.account_instance.ssh_key,
        'project' => @project.id,
        'provider' => @stack.provider,
        'provider_account' => @stack.provider_account,
        'remote_user' => 'ec2-user',
        'private_ip' => provider_info['private_ip'],
        'public_ip' => provider_info['public_ip'],
        'run_list' => stack.run_list || [],
        'stack' => stack.id
      }

      server = Devops::Model::Server.new(server_attrs)
      server.save!
      server
    end

    private

    def server_name_from_info(provider_info)
      builder = ChefNodeNameBuilder.new(
        provider_server_info: provider_info,
        project_id: @project.id,
        env_id: @deploy_env.id,
        owner: stack.owner
      )
      builder.build_node_name!(incrementers_values)
    end

    def incrementers_values
      @incrementers_values ||= {}
    end
  end
end