class Video < ApplicationRecord
  include AASM

  alias_method :hard_destroy, :destroy
  default_scope -> { where(delete_state: nil) }
  scope :deleted, -> { unscope(where: :delete_state).where.not(delete_state: nil) }

  BEGIN_DELETE = 1 # 标记软删除
  FINISH_DELETE = 2 # 视频资源完成删除

  # 标准视频转码组
  NORMAL_TRANSCODE_GROUP_ID = 'a0277c5c0c7458458e171b0cee6ebf5e'

  belongs_to :user

  has_many :video_applies, dependent: :destroy
  has_many :course_videos, dependent: :destroy
  has_one :processing_video_apply, -> { where(status: :pending) }, class_name: 'VideoApply'

  aasm(:status) do
    state :pending, initial: true
    state :processing
    state :refused
    state :published

    event :apply_publish do
      transitions from: :pending, to: :processing
    end

    event :refuse do
      transitions from: :processing, to: :refused
    end

    event :publish do
      transitions from: :processing, to: :published, guard: :vod_uploaded?
    end
  end

  aasm(:vod_status, namespace: :vod) do
    state :uploading, initial: true
    state :uploaded

    event :upload_success do
      transitions from: :uploading, to: :uploaded
    end
  end

  def video_play_duration
    (play_duration / (60*60.0)).ceil
  end

  def destroy
    run_callbacks(:destroy) do
      if persisted?
        update_column(:delete_state, Video::BEGIN_DELETE)
        AliyunVod::Service.delete_video([self.uuid])
      end

      @destroyed = true
    end
    freeze
  end

end