# frozen_string_literal: true module Eancom module Edifact class Message attr_accessor :locations, :items, :hash def initialize @locations = [] @items = [] @hash = {} end def add_location(location) @locations << location end def add_item(item) @items << item end def <<(segment) start_location if segment.starts_location? start_item if segment.starts_item? if @location @location << segment elsif @item @item << segment elsif name = group_name(segment) @hash[name] = [] if @hash[name].nil? @hash[name] << segment.to_json_hash else @hash.merge!(segment.to_json_hash) end end def to_json_hash if @location && !@location.empty? add_location(@location.to_json_hash) end if @item && !@item.empty? add_item(@item.to_json_hash) end message_hash = {} message_hash.merge!(@hash) message_hash.merge!({ locations: @locations }) if !@locations.empty? message_hash.merge!({ items: @items }) if !@items.empty? message_hash end private def group_name(segment) segment.group_name end def start_location if @location && !@location.empty? add_location(@location.to_json_hash) end @location = Eancom::Edifact::Location.new end def start_item if @item && !@item.empty? add_item(@item.to_json_hash) end @item = Eancom::Edifact::Item.new end end end end