module JamRuby

  # describes what users have rights to which tracks
  class JamTrackMixdown < ActiveRecord::Base

    @@log = Logging.logger[JamTrackMixdown]

    belongs_to :user, class_name: "JamRuby::User" # the owner, or purchaser of the jam_track
    belongs_to :jam_track, class_name: "JamRuby::JamTrack"
    has_many :jam_track_mixdown_packages, -> { order('created_at desc') }, class_name: "JamRuby::JamTrackMixdownPackage"#, order: 'created_at DESC'
    has_one :jam_track_right, class_name: 'JamRuby::JamTrackRight', foreign_key: 'last_mixdown_id', inverse_of: :last_mixdown

    validates :name, presence: true, length: {maximum: 100}
    validates :description, length: {maximum: 1000}
    validates :user, presence: true
    validates :jam_track, presence: true
    validates :settings, presence: true

    validates_uniqueness_of :name, scope: [:user_id, :jam_track_id]

    validate :verify_settings
    validate :verify_max_mixdowns

    def self.index(params, user)
      jam_track_id = params[:id]

      limit = 20

      query = JamTrackMixdown.where('jam_track_id = ?', jam_track_id).where('user_id = ?', user.id).order('created_at').paginate(page: 1, per_page: limit)

      count = query.total_entries

      if count == 0
        [query, nil, count]
      elsif query.length < limit
        [query, nil, count]
      else
        [query, start + limit, count]
      end
    end

    def verify_max_mixdowns
      if self.jam_track && self.user && self.jam_track.mixdowns_for_user(self.user).length >= 5
        errors.add(:jam_track, 'allowed 5 mixes')
      end
    end

    def verify_settings

      # the user has to specify at least at least one tweak to volume, speed, pitch, pan.  otherwise there is nothing to do

      #parsed = JSON.parse(self.settings)
      parsed = self.settings
      specified_track_count = parsed["tracks"] ? parsed["tracks"].length : 0

      tweaked = false
      all_quiet = jam_track.stem_tracks.length == 0 ? false : jam_track.stem_tracks.length == specified_track_count # we already say 'all_quiet is false' if the user did not specify as many tracks as there are on the JamTrack, because omission implies 'include this track'


      if parsed["speed"]
        tweaked = true
      end
      if parsed["pitch"]
        tweaked = true
      end


      if parsed["tracks"]
        parsed["tracks"].each do |track|
          if track["mute"]
            tweaked = true
          end
          if track["vol"] && track["vol"] != 0
            tweaked = true
          end
          if track["pan"] && track["pan"] != 0
            tweaked = true
          end

          # there is at least one track with volume specified.
          if !track["mute"] && track["vol"] != 0
            all_quiet = false
          end
        end
      end

      if parsed["count-in"]
        all_quiet = false
        tweaked = true
      end

      if all_quiet
        errors.add(:settings, 'are all muted')
      end
      if !tweaked && !parsed['full']
        errors.add(:settings, 'have nothing specified')
      end

      if parsed["speed"] && !parsed["speed"].is_a?(Integer)
        errors.add(:settings, 'has non-integer speed')
      end

      if parsed["pitch"] && !parsed["pitch"].is_a?(Integer)
        errors.add(:settings, 'has non-integer pitch')
      end
    end

    def self.create(name, description, user, jam_track, settings)
      mixdown = JamTrackMixdown.new
      mixdown.name  = name
      mixdown.description = description
      mixdown.user = user
      mixdown.jam_track = jam_track
      mixdown.settings = settings.to_json # RAILS 4 CAN REMOVE .to_json
      mixdown.save
      mixdown
    end

    def will_pitch_shift?
      self.settings["pitch"] != 0 || self.settings["speed"] != 0
    end

    def self.mixdownChecksum(user_id, jam_track_id)
      dates = self
        .select('created_at')
        .where(user_id:  user_id, jam_track_id: jam_track_id)
        .order(:id)
      
      dates = dates.map do |date|
        date.created_at.to_i.to_s
      end.join('')

      Digest::MD5.hexdigest(dates)
    end

  end
end

