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

  def new
    @matched_file_name = params.delete(:matched_file_name)
    @graphics_element = filtered_graphics_elements.build(graphics_element_params)
    @edl_events_data = build_presenter(@graphics_element.edl_type).present
    @graphics_element.attributes = @edl_events_data[:edl_attributes]
  end

  def create
    graphics_element = filtered_graphics_elements.build(graphics_element_params)
    graphics_element.save
    @graphics_element_data = ::GraphicsElements::GraphicsElementPresenter.new.present(graphics_element)
    @graphics_elements_data = ::GraphicsElements::GraphicsElementsPresenter.new.present(filtered_graphics_elements)
  end

  def edit
    @graphics_element = find_graphics_element
    @video = @graphics_element.video
    @edl_events_data = build_presenter(@graphics_element.edl_type).present
  end

  def update
    graphics_element = find_graphics_element
    graphics_element.update(graphics_element_params)
    @video = graphics_element.video
    @graphics_element_data = ::GraphicsElements::GraphicsElementPresenter.new.present(graphics_element)
    @graphics_elements_data = ::GraphicsElements::GraphicsElementsPresenter.new.present(filtered_graphics_elements)
  end

  def destroy
    graphics_element = find_graphics_element
    @graphics_element_data = ::GraphicsElements::GraphicsElementPresenter.new.present(graphics_element)
    graphics_element.destroy
    @graphics_elements_data = ::GraphicsElements::GraphicsElementsPresenter.new.present(graphics_element.video.graphics_elements)
  end

  private

  def find_graphics_element
    authorize policy_scope(GraphicsElement).find(params[:id])
  end

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

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

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

  def filtered_graphics_elements
    policy_scope(@video.graphics_elements)
  end

  def graphics_element_params
    params.require(:graphics_element).permit(
      :graphic_type,
      :text,
      :time_elapsed,
      :channel,
      :timecode_in,
      :timecode_out,
      :duration,
      :source_file_name,
      :clip_name,
      :description,
      :edl_type,
    )
  end
end
