module JamRuby
  class Mix < ActiveRecord::Base
    MAX_MIX_TIME = 7200     # 2 hours

    before_destroy :delete_s3_files

    self.primary_key = 'id'
    belongs_to :recording, :class_name => "JamRuby::Recording", :inverse_of => :mixes

    def self.schedule(recording, manifest)
      raise if recording.nil?

      mix = Mix.new 
      mix.recording = recording
      mix.manifest = manifest
      mix.save

      mix
    end
    
    def self.next(mix_server)
      # First check if there are any mixes started so long ago that we want to re-run them
      Mix.where("completed_at IS NULL AND started_at < ?", Time.now - MAX_MIX_TIME).each do |mix|
        # FIXME: This should probably throw some kind of log, since it means something went wrong
        mix.started_at = nil
        mix.mix_server = nil
        mix.save
      end

      mix = Mix.where(:started_at => nil).limit(1).first
      return nil if mix.nil?

      mix.started_at = Time.now
      mix.mix_server = mix_server
      mix.save
      
      mix
    end

    def finish(length, md5)
      self.completed_at = Time.now
      self.length = length
      self.md5 = md5
      save
    end

    def s3_url
      S3Manager.s3_url(hashed_filename)
    end

    def url
      S3Manager.url(hashed_filename)
    end
    
    def is_completed
      !completed_at.nil?
    end
    
    private

    def delete_s3_files
      S3Manager.delete(hashed_filename)
    end

    def hashed_filename
      S3Manager.hashed_filename('mix', id)
    end


  end
end
