class VideoReleaseConfirmationsController < ApplicationController
  before_action :set_releasable, except: [:destroy]
  before_action :set_video, except: [:destroy]
  before_action :set_video_release_confirmation, only: [:destroy]

  def new
    @video_release_confirmation = build_video_release_confirmation(video_release_confirmation_params_with_releasable)
    edl_events_presenter = build_presenter
    @edl_events_data = edl_events_presenter.present
    @video_release_confirmation.attributes = @edl_events_data[:edl_attributes]
  end

  def create
    @video_release_confirmation = build_video_release_confirmation(video_release_confirmation_params_with_releasable)
    @video_release_confirmation.save

    set_video_release_confirmations

    respond_to do |format|
      format.html { redirect_to [@video, :video_analyses] }
      format.js
    end
  end

  def destroy
    @releasable = @video_release_confirmation.releasable
    @video = @video_release_confirmation.video

    @video_release_confirmation.destroy

    set_video_release_confirmations

    respond_to do |format|
      format.html { redirect_to [@video_release_confirmation.video, :video_analyses] }
      format.js
    end
  end

  private

  def set_video_release_confirmations
    @video_release_confirmations = @video.video_release_confirmations.order_by_ranked_release_type.order(created_at: :desc)
  end

  def build_presenter
    EdlEventsPresenter.new(
      EdlEventGateway.new(
        FilesForRequest.new(@video),
        @video_release_confirmation.appears_at,
        @video_release_confirmation.appears_at,
        channel_filter: ENV["DISABLE_EDL_CHANNEL_FILTER"] ? "" : "V",
      ))
  end

  def build_video_release_confirmation(attrs = {})
    @video.video_release_confirmations.build(attrs)
  end

  def set_releasable
    releasable_param = ReleasableParam.new(params.to_unsafe_h)

    @releasable = authorize policy_scope(releasable_param.type).find(releasable_param.id)
  end

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

  def set_video_release_confirmation
    @video_release_confirmation = authorize policy_scope(VideoReleaseConfirmation).find(params[:id])
  end

  def video_release_confirmation_params
    params.require(:video_release_confirmation).permit(
      :time_elapsed,
      :file_info_id,
      :channel,
      :timecode_in,
      :timecode_out,
      :duration,
      :source_file_name,
      :clip_name,
      :description
    )
  end

  def video_release_confirmation_params_with_releasable
    video_release_confirmation_params.merge(releasable: @releasable)
  end
end
