# -*- encoding: binary -*-
module Upr

  # Keeps track of the status of all currently processing uploads
  # This uses any {Moneta}[http://github.com/wycats/moneta]
  # store to monitor upload progress.
  #
  # Usage (in config.ru with Moneta Memory store):
  #   require 'upr'
  #   require 'moneta'
  #   use Upr, :backend => Upr::Monitor.new(Moneta.new(:Memory, :serializer => nil))
  #   run YourApplication.new
  class Monitor < Struct.new(:moneta)
    # nuke anything not read/updated in 60 seconds
    OPT = { :expires_in => 60 }

    def initialize(moneta_store = nil)
      super
      if moneta_store.nil?
        self.moneta = Moneta.new(:Memory, :serializer => nil)
      end
    end

    def start(upid, length)
      moneta.store(upid, Status.new(0, length), OPT)
    end

    def read(upid)
      moneta[upid]
    end

    def incr(upid, nr)
      status = moneta[upid] or return
      status.seen += nr if status.seen >= 0
      moneta.store(upid, status, OPT)
    end

    def finish(upid)
      status = moneta[upid] or return
      status.length ||= status.seen
      status.seen = status.length
      moneta.store(upid, status, OPT)
    end

    def error!(upid)
      status = moneta[upid] or return
      status.seen = -1
      moneta.store(upid, status, OPT)
    end

  end
end
