class PendingAnalysis
  def self.poll
    PendingVideoAnalysis.poll
    PendingAudioAnalysis.poll
  end

  def self.expire(age_threshold)
    PendingAudioAnalysis.expire(age_threshold)
    PendingVideoAnalysis.expire(age_threshold)
  end

  class PendingVideoAnalysis
    def initialize(analysis_uid)
      @analysis_uid = analysis_uid
    end

    def self.poll
      Video.
        analysis_pending.
        pluck(:analysis_uid).
        each { |uid| new(uid).poll }
    end

    def self.expire(age)
      Video.
        analysis_pending.
        video_analysis_started_before(age).
        pluck(:analysis_uid).
        each { |video| new(video).expire }
    end

    def poll
      if results_available?
        notification.success!
      end
    end

    def expire
      if results_available?
        notification.success!
      else
        notification.failure!
      end
    end

    private

    attr_reader :analysis_uid

    def notification
      @notification ||= AnalysisNotification.build(:video, analysis_uid)
    end

    def results_available?
      facial_recognition = BrayniacAI::FacialRecognition.find(analysis_uid)
      facial_recognition.respond_to?(:results)
    rescue ActiveResource::ResourceNotFound => e
      false
    rescue ActiveResource::ServerError => e
      message = "-- Video Analysis polling for #{analysis_uid} failed due to: #{e}"
      puts message
      Rails.logger.error(message)
      false
    end
  end

  class PendingAudioAnalysis
    def self.poll
      Video.
        audio_analysis_pending.
        pluck(:audio_analysis_uid).
        each { |uid| new(uid).poll }
    end

    def self.expire(age)
      Video.
        audio_analysis_pending.
        audio_analysis_started_before(age).
        pluck(:audio_analysis_uid).
        each { |uid| new(uid).expire }
    end

    def initialize(analysis_uid)
      @analysis_uid = analysis_uid
    end

    def poll
      if results_available?
        notification.success!
      end
    end

    def expire
      if results_available?
        notification.success!
      else
        notification.failure!
      end
    end

    private

    attr_reader :analysis_uid

    def notification
      @notification ||= AnalysisNotification.build(:audio, analysis_uid)
    end

    def results_available?
      audio_recognition = BrayniacAI::AudioRecognition.find(analysis_uid)
      audio_recognition.respond_to?(:results)
    rescue ActiveResource::ResourceNotFound => e
      false
    rescue ActiveResource::ServerError => e
      message = "-- Audio Analysis polling for #{analysis_uid} failed due to: #{e}"
      puts message
      Rails.logger.error(message)
      false
    end
  end
end
