class VideosController < ApplicationController
  layout "project"

  before_action :set_project, only: [:index, :new, :create, :landing]
  before_action :set_video, only: [:edit, :update]

  def landing
    authorize Video, :new?
  end

  def index
    @videos = filtered_videos.order(created_at: :desc).paginate(page: params[:page])
  end

  def new
    @video = build_video(video_editing_system: params[:video_editing_system])
  end

  def create
    @video = build_video(video_create_params)

    if @video.save
      log_create_analytics
      AnalyzeVideoJob.perform_later(@video)
      AnalyzeAudioJob.perform_later(@video)
      AdminMailer.new_video(@video).deliver_later

      redirect_to [@project, :videos], notice: t(".notice")
    else
      render :new
    end
  end

  def edit
    @project = @video.project
  end

  def update
    @project = @video.project

    if @video.update(video_update_params)
      if edl_file_changed?
        @video.unpublish_report!
        AdminMailer.updated_video_edl_file(@video).deliver_later
      end
      if graphics_only_edl_file_changed?
        @video.unpublish_report!
        AdminMailer.updated_video_graphics_only_edl_file(@video).deliver_later
      end
      if audio_only_edl_file_changed?
        @video.unpublish_report!
        AdminMailer.updated_video_audio_only_edl_file(@video).deliver_later
      end

      redirect_to [@project, :videos], notice: t(".notice")
    else
      render :edit
    end
  end

  private

  def set_project
    @project = policy_scope(Project).find(params[:project_id])
  end

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

  def build_video(params = {})
    authorize videos.build(params)
  end

  def videos
    if @project
      policy_scope(@project.videos)
    else
      policy_scope(Video)
    end
  end


  def filtered_videos
    if params[:query]
      videos.search(params[:query])
    else
      videos
    end
  end

  def edl_file_changed?
    video_update_params.has_key?(:edl_file)
  end

  def graphics_only_edl_file_changed?
    video_update_params.has_key?(:graphics_only_edl_file)
  end

  def audio_only_edl_file_changed?
    video_update_params.has_key?(:audio_only_edl_file)
  end

  def video_create_params
    params.require(:video).permit(
      :name,
      :number,
      :file,
      :edl_file,
      :graphics_only_edl_file,
      :audio_only_edl_file,
      :video_editing_system,
    )
  end

  def video_update_params
    params.require(:video).permit(
      :name,
      :number,
      :edl_file,
      :graphics_only_edl_file,
      :audio_only_edl_file,
    )
  end

  def log_create_analytics
    TrackAnalyticsJob.perform_later(Current.user, Current.account, :track_video_upload, user_agent: request.user_agent, user_ip: request.remote_ip)
  end
end
