# frozen_string_literal: true

require 'tacview_client/base_processor'
require 'time'

module TacScribe
  # Processes the events emitted by the Ruby Tacview Client
  class EventQueue < TacviewClient::BaseProcessor

    attr_accessor :events_written

    def initialize
      @events = Queue.new
      self.events_written = 0
    end

    def clear
      @events.clear
    end

    def size
      @events.size
    end

    def get_event
      @events.shift
    end

    # Process an update event for an object
    #
    # On the first appearance of the object there are usually more fields
    # including pilot names, object type etc.
    #
    # For existing objects these events are almost always lat/lon/alt updates
    # only
    #
    # @param event [Hash] A parsed ACMI line. This hash will always include
    #   the fields listed below but may also include others depending on the
    #   source line.
    # @option event [String] :object_id The hexadecimal format object ID.
    # @option event [BigDecimal] :latitude The object latitude in WGS 84 format.
    # @option event [BigDecimal] :longitude The object latitude in WGS 84
    #   format.
    # @option event [BigDecimal] :altitude The object altitude above sea level
    #   in meters to 1 decimal place.
    def update_object(event)
      self.events_written +=1
      @events << { type: :update_object, event: event, time: @time }
    end

    # Process a delete event for an object
    #
    # @param object_id [String] A hexadecimal number representing the object
    #   ID
    def delete_object(object_id)
      self.events_written +=1
      @events << { type: :delete_object, object_id: object_id }
    end

    # Process a time update event
    #
    # @param time [BigDecimal] A time update in seconds from the
    #   ReferenceTime to 2 decimal places
    def update_time(time)
      @time = @reference_time + time
    end

    # Set a property
    #
    # @param property [String] The name of the property to be set
    # @param value [String] The value of the property to be set
    def set_property(property:, value:)
      case property
      when 'ReferenceLatitude'
        Cache.instance.reference_latitude = BigDecimal(value)
      when 'ReferenceLongitude'
        Cache.instance.reference_longitude = BigDecimal(value)
      when 'ReferenceTime'
        @reference_time = @time = Time.parse(value)
      end
    end
  end
end