class Playlist < ActiveRecord::Base

  include Youtube

  has_permalink(:title, true)

  if Object.const_defined?("Group")
    belongs_to :group
  end

  has_many :videos
  accepts_nested_attributes_for :videos, allow_destroy: true

  validates_presence_of :title, :description

  before_create :create_or_set_youtube_playlist, unless: :offline_mode
  before_update :rename_youtube_playlist, if: :renamable?

  scope :with_videos, ->{
    joins(:videos).where("videos.youtube_video_id is NOT null")
  }

  attr_accessor :offline_mode #whether or not to sync with google

  def to_param
    permalink
  end

  def offline_mode
    @offline_mode ||= AnoGallery.offline_mode
  end

  def youtube_playlist
    @youtube_playlist ||= begin
      pl = self.class.youtube_playlist(title)
      self.class.create_playlist(title, description) unless pl
      pl
    end
  end

  private

  def renamable?
    self.title_changed? && !offline_mode
  end

  def rename_youtube_playlist
    youtube_playlist.update(title: title, description: description)
  rescue Yt::Errors::ServerError, Yt::Errors::RequestError, Yt::Errors::Unauthorized => e
      errors.add :base, e.message
      false
  end

  def create_or_set_youtube_playlist
    self.youtube_playlist_id = youtube_playlist.id
  rescue Yt::Errors::ServerError, Yt::Errors::RequestError, Yt::Errors::Unauthorized => e
      errors.add :base, e.message
      false
  end

  if defined? rails_admin
    rails_admin do
      navigation_label "Media"
      include_all_fields
      visible false
    end
  end

end