unit UServerList;

{$mode delphi}

interface

uses
  Classes, SysUtils, fgl, XMLConf;

type

  { TServerInfo }

  TServerInfo = class
    Name: string;
    Address: string;
    Port: Word;
    PlayersCountCurrent: Integer;
    PlayersCountMax: Integer;
    Password: string;
    MapName: string;
    Latency: TTime;
    procedure Assign(Source: TServerInfo);
    constructor Create;
  end;

  TServerInfos = class(TFPGObjectList<TServerInfo>)
  end;

  { TServerList }

  TServerList = class
    Name: string;
    Address: string;
    Items: TServerInfos;
    procedure Assign(Source: TServerList);
    constructor Create;
    destructor Destroy; override;
    procedure LoadConfig(Config: TXmlConfig; Path: string);
    procedure SaveConfig(Config: TXmlConfig; Path: string);
  end;


implementation

uses
  UGameServer;

{ TServerInfo }

procedure TServerInfo.Assign(Source: TServerInfo);
begin
  Name := Source.Name;
  Address := Source.Address;
  Port := Source.Port;
  PlayersCountCurrent := Source.PlayersCountCurrent;
  PlayersCountMax := Source.PlayersCountMax;
  Password := Source.Password;
  MapName := Source.MapName;
  Latency := Source.Latency;
end;

constructor TServerInfo.Create;
begin
  Port := DefaultServerPort;
end;

{ TServerList }

procedure TServerList.Assign(Source: TServerList);
var
  I: Integer;
begin
  while Items.Count > Source.Items.Count do
    Items.Delete(Items.Count - 1);
  while Items.Count < Source.Items.Count do
    Items.Add(TServerInfo.Create);
  for I := 0 to Items.Count - 1 do begin
    Items[I].Assign(Source.Items[I]);
  end;
end;

constructor TServerList.Create;
begin
  Items := TServerInfos.Create;
end;

destructor TServerList.Destroy;
begin
  Items.Free;
  inherited Destroy;
end;

procedure TServerList.LoadConfig(Config: TXmlConfig; Path: string);
var
  I: Integer;
  Server: TServerInfo;
begin
  Items.Clear;
  Items.Count := Config.GetValue(UnicodeString(Path + '/Count'), 0);
  for I := 0 to Items.Count - 1 do begin
    Server := TServerInfo.Create;
    Server.Name := string(Config.GetValue(UnicodeString(Path + '/Item' + IntToStr(I) + '/Name'), ''));
    Server.Address := string(Config.GetValue(UnicodeString(Path + '/Item' + IntToStr(I) + '/Address'), ''));
    Server.Port := Config.GetValue(UnicodeString(Path + '/Item' + IntToStr(I) + '/Port'), 0);
    Items[I] := Server;
  end;
end;

procedure TServerList.SaveConfig(Config: TXmlConfig; Path: string);
var
  I: Integer;
  Server: TServerInfo;
begin
  Config.SetValue(UnicodeString(Path + '/Count'), Items.Count);
  for I := 0 to Items.Count - 1 do begin
    Server := Items[I];
    Config.SetValue(UnicodeString(Path + '/Item' + IntToStr(I) + '/Name'), UnicodeString(Server.Name));
    Config.SetValue(UnicodeString(Path + '/Item' + IntToStr(I) + '/Address'), UnicodeString(Server.Address));
    Config.SetValue(UnicodeString(Path + '/Item' + IntToStr(I) + '/Port'), Server.Port);
  end;
end;

end.

