module Devops
  module Model
    class JobTask

      include ::Mongoid::Document
      include ::Mongoid::Timestamps::CreatedInt
      include ::Mongoid::Timestamps::UpdatedInt
      include ::ActiveModel::Validations

      store_in collection: "job_tasks"


      DEPLOY_SERVER_TYPE = 1
      CREATE_SERVER_TYPE = 2
      BOOTSTRAP_TYPE = 3
      PROJECT_TEST_TYPE = 4
      STACK_TYPE = 5
      DEPLOY_STACK_TYPE = 6
      DELETE_SERVER_TYPE = 7
      EXPIRE_SERVER_TYPE = 8
      SYNC_STACK_TYPE = 9
      UNBOOTSTRAP_TYPE = 10

      SYSTEM_OWNER = 'SYSTEM'

      field :_id, as: :'id', overwrite: true, type: String
      field :file, type: String
      field :project, type: String
      field :environment, type: String
      field :category, type: String
      field :created_by, type: String
      field :type, type: Integer
      field :server_id, type: String
      field :host, type: String
      field :status, type: String
      field :stack, type: String
      field :subtasks, type: Array
      field :job_result_code, type: Integer
      field :bootstrap_info, type: Hash
      field :deploy_info, type: Hash

      def to_hash
        hash = self.attributes.clone
        hash["id"] = hash.delete("_id")
        hash.delete("file")
        hash
      end

      def add_subtasks(jid, subtasks)
        JobTask.where(_id: jid).push_all("subtasks" => subtasks)
      end

      index(created_at: 1)
      index(project: 1, environment: 1, created_at: 1)
    end
  end
end
