class ApiJamTrackMixdownsController < ApiController

  # have to be signed in currently to see this screen
  before_filter :api_signed_in_user
  before_filter :lookup_jam_track_mixdown, :only => [:download, :enqueue, :update]
  before_filter :lookup_jam_track_right, :only => [:download, :enqueue, :update]
  before_filter :ip_blacklist, :only => [:download]
  before_filter :user_blacklist, :only => [:download]
  respond_to :json

  def log
    @log || Logging.logger[ApiJamTrackMixdownsController]
  end

  def index
    data = JamTrackMixdown.index(params, current_user)
    @jam_track_mixdowns, @next, @count = data[0], data[1], data[2]

    render "api_jam_track_mixdowns/index", :layout => nil
  end

  def show
    @jam_track_mixdown = JamTrackMixdown.find(params[:id])
  end

  def delete
    @jam_track_mixdown = JamTrackMixdown.find(params[:id])
    @jam_track_mixdown.destroy
    render json: {}, status:204
  end

  def update
    @mixdown = JamTrackMixdown.find(params[:id])
    @mixdown.name = params[:name] if params[:name]
    @mixdown.description = params[:description] if params[:description]
    @mixdown.save
    if params[:active]
      @jam_track_right.last_mixdown = @mixdown
      @jam_track_right.save
    end

    if @mixdown.errors.any?
      respond_with_model(@mixdown)
      return
    else

    end
  end

  def show_package
    @package = JamTrackMixdownPackage.find(params[:id])
  end

  def create
    @mixdown = JamTrackMixdown.create(params[:name], params[:description], current_user, JamTrack.find(params[:jamTrackID]), params[:settings])

    if @mixdown.errors.any?
      respond_with_model(@mixdown)
      return
    end

  end

  def download
    if current_user.email_needs_verification
      render :json => { :message => "verify email" }, :status => 403
      return
    end

    if @jam_track_right.valid?

      begin
        @package = JamTrackMixdownPackage.where('jam_track_mixdown_id = ?', @jam_track_mixdown.id).where(file_type: params[:file_type]).where(encrypt_type: params[:encrypt_type]).where(sample_rate: params[:sample_rate]).first

      rescue Exception => e
        log.error("failed to find mixdown package", e)
        render :json => {:message => "unable to locate mixdown package due to error; check arguments"}, :status => 404
        return
      end

      @package = JamTrackMixdownPackage.create(@jam_track_mixdown, params[:file_type], params[:sample_rate], params[:encrypt_type]) unless @package

      if @package.errors.any?
        respond_with_model(@package)
        return
      end

      if @package.ready?

        @package.update_download_count
        now = Time.now
        @package.last_downloaded_at = now
        @package.first_downloaded_at = now if @package.first_downloaded_at.nil?
        @package.save!

        if params[:download]
          if DownloadTracker.check(current_user, request.remote_ip, @package, !@jam_track_right.redeemed, params[:mark], false)
            render :json => { :message => "IP blacklisted"}, :status => 403
            return
          end
          redirect_to @package.sign_url(120, 'application/octet-stream', "attachment; filename=\"#{@package.jam_track_mixdown.name}.#{params[:file_type]}\"")
        else
          if DownloadTracker.check(current_user, request.remote_ip, @package, !@jam_track_right.redeemed, params[:mark], true)
            render :json => { :message => "IP blacklisted"}, :status => 403
            return
          end
          redirect_to @package.sign_url(120)
        end


      else
        @package.enqueue_if_needed
        render :json => { :message => "not available, digitally signing Jam Track Mixdown offline." }, :status => 202
      end
    else
      render :json => { :message => "download limit surpassed", :errors=>@package.errors }, :status => 403
    end
  end

  def enqueue
    if @jam_track_right.valid?

      begin
        @package = JamTrackMixdownPackage.where('jam_track_mixdown_id = ?', @jam_track_mixdown.id).where(file_type: params[:file_type]).where(encrypt_type: params[:encrypt_type]).where(sample_rate: params[:sample_rate]).first
      rescue Exception => e
        puts "enqueue failure #{e}"
        log.error("failed to find mixdown package #{e}")
        render :json => {:message => "unable to locate mixdown package due to error; check arguments"}, :status => 404
        return
      end

      @package = JamTrackMixdownPackage.create(@jam_track_mixdown, params[:file_type], params[:sample_rate], params[:encrypt_type]) unless @package

      if @package.errors.any?
        respond_with_model(@package)
        return
      end

      enqueued = @package.enqueue_if_needed
      log.debug("jamtrack mixdown #{enqueued ? "ENQUEUED" : "NOT ENQUEUED"}: mixdown_package=#{@package.id} ")
      @queue_time = enqueued ? enqueued : 0
      return
    else
      render :json => { :message => "download limit surpassed", :errors=>@package.errors }, :status => 403
    end

  end

  private
  def lookup_jam_track_right
    @jam_track_right = JamTrackRight.where("jam_track_id=? AND user_id=?", @jam_track_mixdown.jam_track.id, current_user.id).first
    raise JamPermissionError, ValidationMessages::PERMISSION_VALIDATION_ERROR unless @jam_track_right
  end

  def lookup_jam_track_mixdown
    @jam_track_mixdown = JamTrackMixdown.find(params[:id])
  end

end # class ApiJamTracksController
