require_relative "worker"

class DeployWorker < Worker

  # options must contain 'server_attrs', 'owner', 'tags', 'deploy_info'
  def perform(options)
    server_id = options.fetch('server_id')
    owner = options.fetch('owner')
    tags = options.fetch('tags')
    deploy_info = options.fetch('deploy_info')

    call do |out, task|
      server = Devops::Model::Server.find(server_id)
      task_data = {
        "created_by" => owner,
        "project" => server.project,
        "environment" => server.environment,
        "server_id" => server.id,
        "category" => server.category,
        "host" => server.public_ip || server.private_ip
      }
      if server.stack.nil?
        task_data["type"] = Devops::Model::JobTask::DEPLOY_SERVER_TYPE
      else
        task_data["type"] = Devops::Model::JobTask::DEPLOY_STACK_TYPE
        task_data["stack"] = server.stack
      end

      set_task_data(task_data)

      executor = Devops::Executor::ServerExecutor.new(server, out, owner)
      executor.job_task = task
      status = begin
        info = executor.deploy_info(server_attrs)
        executor.deploy_server server_attrs, info
        #executor.deploy_server_with_tags(tags, deploy_info)
        0
      rescue Devops::Exception::ServerOperationError => e
        msg = e.message
        DevopsLogger.logger.error msg
        e.error_code
      end
      out.puts msg
      out.flush
      status
    end
  end

end
