require "defines"

BRAKING_HONK = "train-honk-long-single"
STARTING_HONK = "train-honk-short-double"

HONK_ON_START = true
HONK_FOR_STATION = true
HONK_FOR_SIGNAL = true

function playSoundAtEntity(sound, entity)
  entity.surface.create_entity({name = sound, position = entity.position})
end

--[[
trainstate =
{
  --? Normal state -- following the path.
  on_the_path = 0,
  --? Had path and lost it -- must stop.
  path_lost = 1,
  --? Doesn't have anywhere to go.
  no_schedule = 2,
  --? Has no path and is stopped.
  no_path = 3,
  --? Braking before a rail signal.
  arrive_signal = 4,
  --? Waiting at a signal.
  wait_signal = 5,
  --? Braking before a station.
  arrive_station = 6,
  --? Waiting at a station.
  wait_station = 7,
  --? Switched to manual control and has to stop.
  manual_control_stop = 8,
  --? Can move if user explicitly sits in and rides the train.
  manual_control = 9,
  --? Train was switched to auto control but it is moving and needs to be stopped.
  stop_for_auto_control = 10
}
--]]

script.on_event(defines.events.on_train_changed_state, function(event)
  if HONK_ON_START and event.train.state == defines.trainstate.on_the_path then
    playSoundAtEntity(STARTING_HONK, event.train.locomotives.front_movers[1])
  elseif HONK_FOR_STATION and event.train.state == defines.trainstate.arrive_station then
    playSoundAtEntity(BRAKING_HONK, event.train.locomotives.front_movers[1])
  elseif HONK_FOR_SIGNAL and event.train.state == defines.trainstate.arrive_signal then
    playSoundAtEntity(BRAKING_HONK, event.train.locomotives.front_movers[1])
  end
end)