class VideoAnalyses::UnreleasedAppearancesController < ApplicationController
  before_action :set_video, except: [:edit, :update, :destroy]

  def new
    @unreleased_appearance = @video.unreleased_appearances.build(unreleased_appearance_params)
    @edl_events_data = build_presenter.present
    @unreleased_appearance.attributes = @edl_events_data[:edl_attributes]
  end

  def create
    @unreleased_appearance = @video.unreleased_appearances.build(unreleased_appearance_params)
    @unreleased_appearance.save
    @unreleased_appearances_data = UnreleasedAppearancesPresenter.new.present(@video.unreleased_appearances)
  end

  def edit
    @unreleased_appearance = find_unreleased_appearance
    @video = @unreleased_appearance.video
    @edl_events_data = build_presenter.present
  end

  def update
    unreleased_appearance = find_unreleased_appearance
    unreleased_appearance.update(unreleased_appearance_params)
    @unreleased_appearances_data = UnreleasedAppearancesPresenter.new.present(unreleased_appearance.video.unreleased_appearances)
  end

  def destroy
    unreleased_appearance = find_unreleased_appearance
    video = unreleased_appearance.video
    unreleased_appearance.destroy
    @unreleased_appearances_data = UnreleasedAppearancesPresenter.new.present(video.unreleased_appearances)
  end

  private

  def build_presenter
    EdlEventsPresenter.new(EdlEventGateway.new(FilesForRequest.new(@video), @unreleased_appearance.appears_at, @unreleased_appearance.appears_at))
  end

  def unreleased_appearance_params
    params
      .require(:unreleased_appearance)
      .permit(
        :notes,
        :time_elapsed,
        :channel,
        :timecode_in,
        :timecode_out,
        :duration,
        :source_file_name,
        :clip_name,
        :description,
        :note_category
      )
  end

  def unreleased_appearances
    if @video
      policy_scope(@video.unreleased_appearances)
    else
      policy_scope(UnreleasedAppearance)
    end
  end

  def videos
    policy_scope(Video)
  end

  def find_unreleased_appearance
    authorize unreleased_appearances.find(params[:id])
  end

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