-- environment_ers_mtn.lua
if S.trains == nil then S.trains = {} end
if S.d == nil then S.d = {} end
if S.datetime == nil then S.datetime = "" end
if S.stop_display == nil then S.stop_display = false end

F.print = function (str) if F.debug then print("".. (str or "nil") ) end end
F.isempty = function (s) return s == nil or s == "" end
F.get_rc_safe = function() return get_rc() or "" end
F.get_line_safe = function() return get_line() or "" end
F.get_train_length_safe = function() return train_length() or 0 end
F.avg = function(t)
  local sum = 0
  local count = 0
  for k,v in pairs(t) do
    if type(v) == "number" then
      sum = sum + v
      count = count + 1
    end
  end
  return (sum / count)
end

if event.init then
  F.debug = true
  F.printAllTrainsInfo = true
  F.max_displays = 3
  F.print("Initialized")
end

--[[
  EXAMPLE: F.has_rc("LILSHUNTER", F.get_rc_safe() )
  Merged F.has_rc and F.does_train_have_rc
  F.does_train_have_rc is deprecated
]]
F.has_rc = function(query,rc_list) -- query = string, single entry
  for word in rc_list:gmatch("[^%s]+") do
    if word == query then return true end
  end
  return false
end

F.send_route = function(passive_name, route, show_print)
  local message = ""
  local return_value = false
  if can_set_route(passive_name, route) then
    set_route(passive_name, route)
    message = passive_name .. " has been set to " .. route
    return_value = true
  else
    message = route .. " cannot be set for " .. passive_name .. ". Try another."
    return_value = false
  end
  if show_print == true then F.print(message) end
  return return_value
end

F.save_train = function(pos)
  if not atc_id then return end
  if S.trains then
    if F.isempty(pos) then
      pos_string = ""
    else
      pos_string = pos["x"] .. "," .. pos["y"] .. "," .. pos["z"]
    end
    -- if F.has_rc("FAREAST", F.get_rc_safe()) then
      S.trains[atc_id] = { ["id"] = atc_id, ["rc"] = F.get_rc_safe(), ["ln"] = F.get_line_safe(), ["cars_count"] = F.get_train_length_safe(), ["pos"] = pos_string }
      -- F.print("Train ID: " .. S.trains[atc_id]["id"] .. " at " .. S.trains[atc_id]["pos"])
      -- remote_track = POS(30919,13,1812)
      -- interrupt_pos(remote_track, "display")
    -- end
  end
end

F.get_real_split_count = function(train_length_count, split_count)
  if split_count then
    if split_count == "all" then
      return 2
    else
      F.print("train_length_count (" .. train_length_count .. ") - split_count (" .. split_count .. ")")
      train_length_count = train_length_count + 1
      split_count = train_length_count - split_count
      return split_count
    end
  else
    return nil
  end
end

F.delete_train_info = function(train_id)
  if S.trains[train_id] then
    S.trains[train_id] = nil
    F.print("Deleted train id: " .. train_id)
  end
end

F.clear_main_depot_displays = function() for i = 1, F.max_displays, 1 do digiline_send("train_display" .. i, " ") end end
F.send_update_displays = function() for i = 1, F.max_displays, 1 do digiline_send("train_display" .. i, "Updating...") end end

F.date_formatted = function()
  date = os.date("%Y-%m-%d")
  return date
end

F.time_formatted = function()
  time = os.date("*t")
  return string.format("%02d:%02d:%02d %s", time.hour, time.min, time.sec, (time.isdst and "CEST") or "CET")
end

F.list_trains = function(print_info)
  if S.trains then
    number_of_displays = F.max_displays
    F.clear_main_depot_displays()
    number_of_displays = number_of_displays + 1
    count_keys = 0
    trains_table = {}
    for k in pairs(S.trains) do
      table.insert(trains_table, k)
      count_keys = count_keys + 1
    end
    table.sort(trains_table)
    -- x = number_of_displays - count_keys
    x = 1

    for _, k in ipairs(trains_table) do
      if S.trains[k] then
        v = S.trains[k]
        if F.has_rc("LILSHUNTER", v["rc"]) or F.has_rc("LIL", v["rc"]) then
          F.delete_train_info(v["id"])
        else
          if v["ln"] == nil or v["ln"] == "" then
            line_number = ""
          else
            line_number = "| LN: [" .. v["ln"] .. "]"
          end
          if v["pos"] == nil or v["pos"] == "" then
            pos_string = ""
          else
            pos_string = "| POS: [" .. v["pos"] .. "]"
          end
          if v["rc"] == nil or v["rc"] == "" then
            rc_display = ""
          else
            rc_list = v["rc"]
            rc_list_cleansed = ""
            rc_list_unknown = ""
            rc_list_table = {}
            if F.has_rc("ERSTAZI", rc_list) and F.has_rc("FREIGHT", rc_list) then
              rc_list_cleansed = "ERSTAZI FREIGHT |"
            else
              rc_list_cleansed = "NO E,F |"
            end
            for rc in rc_list:gmatch("[^%s]+") do
              if rc == "ERSTAZI" or rc == "FREIGHT" then
                -- leaving for future use
                do_nothing = true
              else
                rc_list_unknown = rc_list_unknown .. " " .. rc
              end
            end
            rc_display = ""
            if not F.isempty(rc_list_unknown) then
              rc_display = rc_display .. "| RC:" .. rc_list_unknown
            end
          end
          if v["cars_count"] == nil or v["cars_count"] == "" then
            cars_count_display = " Len: 0"
          else
            cars_count = tonumber(v["cars_count"])
            cars_count_display = " Len: " .. cars_count
          end
          message = " ID: " .. v["id"] .. cars_count_display .. rc_display ..  line_number .. pos_string
          if x > 0 then digiline_send("train_display" .. x, message) end
          if print_info then
            F.print(x .. ": " .. message)
          end
          x = x + 1
        end
      end
    end

    -- S.datetime = os.date("%Y-%m-%d %H:%M:%S")
    -- digiline_send("time", "  \n    " .. S.datetime)

  else
    if print_info then
      F.print("no trains saved in S.trains")
    end
  end
end

F.slow_train_down = function(id)
  result = atc_send_to_train(id, "B1")
  if result == false then
    F.print("Train ID " .. id .. " does not exist")
  else
    F.print("Train ID " .. id .. " is slowed down to B1")
  end
end