require_relative 'amount'

module Rledger
  # Entry contains the specification of an operation on an account
  #
  # Entries are the basis for Transactions.
  #
  # We allow for operations with no amount, in which case the amount
  # is computed from remaining entries in the Transaction (see the 
  # class Transaction)
  #
  class Post
    attr_accessor :voice, :amount, :comment

    def initialize
      @voice = ""
      @amount = Amount.new
      @comment = ""
    end

    def parse(s)
      voice = "([a-zA-Z:-_!@']+)"
      amount = "([^;]*|)"  # a regexp which allows to move to the next token
      comment = ";? ?(.*|)"
      b = "[\t ]+"
      ob = "[\t ]*"
      
      match = Regexp.new(b + voice + ob + amount + ob + comment).match(s)

      if match
        @voice = match[1]
        @amount.parse(match[2])
        @derived = match[2] == ""
        @comment = match[3]
        true
      else
        false
      end
    end

    def derived?
      @derived
    end

    def to_s
      "\t#{@voice}#{amount_to_s}\t#{comment_to_s}\n"
    end

    private

    def amount_to_s
      derived? ? "" : "\t#{@amount.to_s}"
    end

    def comment_to_s
      @comment == "" ? "" : "; #{@comment}"
    end
  end
end
