module JamRuby
  class ClaimedRecording < ActiveRecord::Base

    validates :name, no_profanity: true

    belongs_to :recording, :class_name => "JamRuby::Recording", :inverse_of => :claimed_recordings
    belongs_to :user, :class_name => "JamRuby::User", :inverse_of => :claimed_recordings
    belongs_to :genre, :class_name => "JamRuby::Genre"
    has_many :recorded_tracks, :through => :recording, :class_name => "JamRuby::RecordedTrack"

    # user must own this object
    # params is a hash, and everything is optional
    def update_fields(user, params)
      if user != self.user
        raise PermissionError, "user doesn't own claimed_recording"
      end

      self.name = params[:name] unless params[:name].nil?
      self.genre = Genre.find(params[:genre]) unless params[:genre].nil?
      self.is_public = params[:is_public] unless params[:is_public].nil?
      self.is_downloadable = params[:is_downloadable] unless params[:is_downloadable].nil?
      save
    end

    def discard(user)
      if user != self.user
        raise PermissionError, "user doesn't own claimed_recording"
      end
      
      # If this is the only copy, destroy the entire recording. Otherwise, just destroy this claimed_recording
      if recording.claimed_recordings.count == 1
        recording.discard
      else
        self.destroy
      end
    end
  end
end
