class VideoAnalyses::AudioConfirmationsController < ApplicationController
  before_action :set_video, only: [:new, :create]

  def new
    @matched_file_name = params.delete(:matched_file_name)
    @audio_confirmation = filtered_audio_confirmations.build(audio_confirmation_params)
    @edl_events_data = build_presenter(@audio_confirmation.edl_type).present
    @audio_confirmation.attributes = @edl_events_data[:edl_attributes]
  end

  def create
    audio_confirmation = filtered_audio_confirmations.build(audio_confirmation_params)
    audio_confirmation.save
    @audio_confirmation_data = ::AudioConfirmations::AudioConfirmationPresenter.new.present(audio_confirmation)
    @audio_confirmations_data = ::AudioConfirmations::AudioConfirmationsPresenter.new.present(filtered_audio_confirmations)
  end

  def destroy
    audio_confirmation = find_audio_confirmation
    video = audio_confirmation.video
    audio_confirmation.destroy
    @audio_confirmation_data = ::AudioConfirmations::AudioConfirmationPresenter.new.present(audio_confirmation)
    @audio_confirmations_data = ::AudioConfirmations::AudioConfirmationsPresenter.new.present(video.audio_confirmations)
  end

  private

  def build_presenter(edl_type)
    files_for_request = if edl_type == "all_tracks"
                          FilesForRequest.new(@video)
                        else
                          AudioFilesForRequest.new(@video, @video.edl_timecode_start)
                        end

    EdlEventsPresenter.new(
      EdlEventGateway.new(
        files_for_request,
        @audio_confirmation.appears_at,
        @audio_confirmation.appears_at,
        channel_filter: ENV["DISABLE_EDL_CHANNEL_FILTER"] ? "" : "A",
      )
    )
  end

  def find_audio_confirmation
    authorize policy_scope(AudioConfirmation).find(params[:id])
  end

  def set_video
    @video = authorize policy_scope(Video).find(params[:video_id])
  end

  def filtered_audio_confirmations
    policy_scope(@video.audio_confirmations)
  end

  def audio_confirmation_params
    params.require(:audio_confirmation).permit(
      :time_elapsed,
      :channel,
      :timecode_in,
      :timecode_out,
      :duration,
      :source_file_name,
      :clip_name,
      :description,
      :music_type,
      :music_category,
      :composer_info,
      :publisher_info,
      :catalog,
      :title,
      :confirmation_type,
      :edl_type,
    )
  end
end
