require 'debci/db'
require 'debci/package'
require 'debci/job'
require 'debci/experiment_test'

module Debci
  class Debci::Experiment < ActiveRecord::Base
    serialize :package_selector, type: Hash
    serialize :control_parameters, type: Hash
    serialize :test_parameters, type: Hash

    has_many :tests, class_name: 'Debci::ExperimentTest'
    belongs_to :owner, class_name: 'Debci::User'

    def packages
      @packages ||= Debci::Package.where(**self.package_selector)
    end

    def start
      packages.each do |package|
        control_job = Debci::Job.create!(
          suite: suite,
          arch: arch,
          package: package,
          requestor: owner,
          **Hash(self.control_parameters)
        )
        test_job = Debci::Job.create!(
          suite: suite,
          arch: arch,
          package: package,
          requestor: owner,
          **Hash(self.test_parameters),
        )
        tests.create!(control_job: control_job, test_job: test_job)
        control_job.enqueue(priority)
        test_job.enqueue(priority)
      end
      update(started_at: Time.now)
    end

    def started?
      !started_at.blank?
    end
  end
end
