module JamRuby
  class UserSync < ActiveRecord::Base

    belongs_to :recorded_track
    belongs_to :mix
    belongs_to :quick_mix
    belongs_to :recorded_backing_track

    def self.show(id, user_id)
      self.index({user_id: user_id, id: id, limit: 1, offset: 0})[:query].first
    end

    def self.index(params)
      user_id = params[:user_id]
      limit = params[:limit].to_i
      limit = limit == 0 ? 20 : limit
      offset = params[:offset].to_i
      id = params[:id]
      recording_id = params[:recording_id]

      page = (offset / limit) + 1 # one-based madness

      raise 'no user id specified' if user_id.blank?

      query = UserSync
        .includes(recorded_track: [{recording: [:owner, {claimed_recordings: [:share_token]}, {recorded_tracks: [:user]}, {comments:[:user]}, :likes, :plays, :mixes]}, user: [], instrument:[]], mix: [], quick_mix:[], recorded_backing_track:[])
        .joins("LEFT OUTER JOIN claimed_recordings ON claimed_recordings.user_id = user_syncs.user_id AND claimed_recordings.recording_id = user_syncs.recording_id")
        .where(user_id: user_id)
        .where(%Q{
          ((claimed_recordings IS NULL OR claimed_recordings.discarded = TRUE) AND fully_uploaded = FALSE) OR (claimed_recordings IS NOT NULL AND claimed_recordings.discarded = FALSE)
        })
        .paginate(:page => page, :per_page => limit)
        .order('created_at DESC, unified_id')


      # allow selection of single user_sync, by ID
      unless id.blank?
        query = query.where(unified_id: id)
      end

      unless recording_id.blank?
        query = query.where(recording_id: recording_id)
      end

      if query.length == 0
        { query:query, next: nil}
      elsif query.length < limit
        { query:query, next: nil}
      else
        { query:query, next: offset + limit}
      end
    end


    def self.deletables(params)
      user_id = params[:user_id]
      recording_ids = params[:recording_ids]

      limit = 1000

      if recording_ids.nil?
        return []
      else
        recording_ids = recording_ids.uniq

        raise "too many recording_ids" if recording_ids.length > limit

        found_recording_ids  =
          UserSync
          .select('user_syncs.recording_id')
          .joins("LEFT OUTER JOIN claimed_recordings ON claimed_recordings.user_id = user_syncs.user_id")
          .where(%Q{
            ((claimed_recordings IS NULL OR claimed_recordings.discarded = TRUE) AND fully_uploaded = FALSE) OR (claimed_recordings IS NOT NULL AND claimed_recordings.discarded = FALSE)
          })
          .where(user_id: user_id)
          .paginate(:page => 1, :per_page => limit)
          .group('user_syncs.recording_id').map(&:recording_id)

        recording_ids - found_recording_ids
      end
    end
  end
end

