##
# Regenerates bindings.cpp and module.yml.

require 'json'
require 'yaml'

STEAMWORKS_DIR = File.expand_path('../../../../deps/steamworks/sdk', __dir__)

bindings_header_path = File.expand_path('bindings.h', __dir__)
bindings_code_path = File.expand_path('bindings.cpp', __dir__)
yml_path = File.expand_path('module.yml', __dir__)

header = JSON.parse(File.open(File.join(STEAMWORKS_DIR, 'public/steam/steam_api.json')).read)

commands = []

def c_to_bb_sym(type)
  '%'
end

def c_to_bb(type)
  type
end

File.open(bindings_code_path, 'w') do |f|
  f.write "// AUTOGENERATED. DO NOT EDIT.\n"
  f.write "// RUN `ruby src/modules/bb/steamworks/generate.rb` TO UPDATE.\n\n"

  f.write %(#include "steamworks.h"\n\n)

  header['interfaces'].each do |iface|
    iface['methods'].each do |method|
      ident = method['methodname_flat']
      symbol = "bb#{ident}"

      params = method['params'].map do |param|
        type = param['paramtype']
        type = 'uint64_steamid' if type == 'CSteamID'
        type = 'uint64_gameid' if type == 'CGameID'

        {
          name: param['paramname'],
          c_type: c_to_bb(type),
          bb_type: c_to_bb_sym(param['paramtype'])
        }
      end

      params.unshift(name: 'Self', c_type: "#{iface['classname']} *", bb_type: '%')

      commands << {
        decl: "#{c_to_bb(method['returntype'])} #{symbol}( #{params.map { |p| "#{p[:c_type]} #{p[:name]}" }.join(', ')} )",
        link: %(#{ident}(#{params.map { |p| "#{p[:name]}#{p[:bb_type]}" }.join(',')}):"#{symbol}")
      }

      f.write "#{commands.last[:decl]}{\n"

      f.write "  "

      if method['returntype'] != 'void'
        f.write "return "
      end

      f.write "#{ident}( #{params.map { |p| p[:name] }.join(',')} );\n"

      f.write "}\n\n"
    end
  end
end

File.open(bindings_header_path, 'w') do |f|
  f.write "// AUTOGENERATED. DO NOT EDIT.\n"
  f.write "// RUN `ruby src/modules/bb/steamworks/generate.rb` TO UPDATE.\n\n"

  commands.each do |cmd|
    f.write "  #{cmd[:decl]};\n"
  end
end


mod = {
  'name' => 'Steamworks',
  'description' => 'Bindings for the Steamworks SDK',
  'platforms' => [
    'win64',
    'macos',
    'linux'
  ],
  'commands' => commands.map { |c| c[:link] }
}

File.open(yml_path, 'w') do |f|
  f.write "##\n"
  f.write "# AUTOGENERATED. DO NOT EDIT.\n"
  f.write "# RUN `ruby src/modules/bb/steamworks/generate.rb` TO UPDATE.\n\n"

  f.write YAML.dump(mod).gsub(/^\-\-\-\n/, '')
end
