class LiveLinksController < ApplicationController
  before_action :require_login
  before_action :find_course, only: [:index, :create]
  before_action :user_course_identity, :teacher_allowed, only: [:create]
  before_action :edit_auth, only: [:edit, :update]
  before_action :delete_auth, only: [:destroy]

  def index
    lives = @course.live_links
    order_str = "on_status desc, live_time desc"
    @total_count = lives.size
    @my_live_id = @course.live_links.find_by(user_id: current_user.id)&.id
    # order_str = "live_links.id = #{@my_live_id} desc, #{order_str}" if @my_live_id.present?
    lives = lives.order("#{order_str}")
    @lives = paginate lives.includes(user: :user_extension)
  end

  def create
    on_status = params[:live_time].present? && params[:live_time].to_time <= Time.now ? 1 : 0
    @course.live_links.create!(create_params.merge(user_id: current_user.id, on_status: on_status))
    render_ok
  end

  def edit
    @live = current_live
  end

  def update
    if params[:on_status]
      tip_exception("请勿重复开启") if current_live.on_status && params[:on_status].to_i == 1

      ActiveRecord::Base.transaction do
        current_live.update!(on_status: params[:on_status])

        # 开启时发送消息，关闭直播时删除对应的消息
        if params[:on_status].to_i == 1
          LivePublishJob.perform_later(current_live.id)
        end
      end
    else
      on_status = params[:live_time].present? && params[:live_time].to_time <= Time.now ? 1 : 0
      current_live.update!(create_params.merge(on_status: on_status))
    end
    render_ok
  end

  def destroy
    current_live.destroy!
    render_ok
  end

  private

  def create_params
    params.permit(:url, :description, :course_name, :platform, :live_time, :duration)
  end

  def current_live
    @_current_live = LiveLink.find params[:id]
  end

  def edit_auth
    tip_exception(403, "无权限操作") unless current_user.id == current_live.user_id || current_user.admin_or_business?
  end

  def delete_auth
    tip_exception(403, "无权限操作") unless current_user.id == current_live.user_id || current_user.admin?
  end
end