class EdlEventGateway
  def initialize(files_for_request, timecode_start, timecode_end, collection: {}, channel_filter: "")
    @files_for_request = files_for_request
    @timecode_start = timecode_start
    @timecode_end = timecode_end
    @collection = collection
    @channel_filter = channel_filter
  end

  def edl_events
    @edl_events ||= response_results.
      filter { |response_edl_event| response_edl_event.channel.include?(channel_filter) }.
      map do |response_edl_event|
      EdlEvent.new(
        channel: response_edl_event.channel,
        start_time: response_edl_event.start_time,
        timecode_in: response_edl_event.timecode_in,
        timecode_out: response_edl_event.timecode_out,
        duration: response_edl_event.duration,
        source_file_name: response_edl_event.source_file_name,
        clip_name: response_edl_event.clip_name,
        description: response_edl_event.description,
        matches: response_edl_event.matches,
      )
    end
  end

  def edl_timecode_start
    return if response.nil?

    response.edl_timecode_start
  end

  def fps
    return if response.nil?

    response.fps
  end

  def edl_offset_seconds
    return if response.nil?

    response.edl_offset_seconds
  end

  private

  attr_reader :files_for_request, :timecode_start, :timecode_end, :collection, :channel_filter

  def as_json(*)
    {
      job_id: files_for_request.job_id,
      video_bucket_name: files_for_request.aws_bucket_name,
      video_object_name: files_for_request.file_object_name,
      edl_bucket_name: files_for_request.aws_bucket_name,
      edl_object_name: files_for_request.edl_file_object_name,
      timecode_start: timecode_start,
      timecode_end: timecode_end,
      collection: collection,
      edl_timecode_start: files_for_request.start_timecode_offset,
    }.compact
  end

  def response_results
    return [] if response.nil?

    response.results
  end

  def response
    @response ||= BrayniacAI::EdlParse.create as_json
  rescue ActiveResource::ServerError => e
    nil
  end
end
