module Unitwise
  module Expression
    class Decomposer
      class << self
        def reset(n = {})
          old = {
            parsers: @parsers,
            transformer: @transformer,
            cache: @cache
          }
          @parsers = n[:parsers]
          @transformer = n[:transformer]
          @cache = n[:cache]
          old
        end
      end
    end
  end

  def self.with_custom_units(unit_list, &block)

    if unit_list.empty?
      return block.call
    end

    atoms = []
    ret_val = nil

    begin
      unit_list.each do |u|
        atom = Unitwise::Atom.new(u)
        atom.validate!
        Unitwise::Atom.all.push(atom)
        atoms.push(atom)
      end
      rem = Unitwise::Expression::Decomposer.send(:reset)

      ret_val = block.call
    ensure
      atoms.each do |a|
        idx = Unitwise::Atom.all.index { |b| b.equal?(a) }
        Unitwise::Atom.all.delete_at(idx)
        # Unitwise::Atom.all.pop
      end
      Unitwise::Expression::Decomposer.send(:reset, rem)
    end

    ret_val
  end
end