function TableCallback(event)
% TableCallback - Callback called by the modelit.webserver.Server object
% for displaying an AG-GRID table in an HTML page.
%
% CALL:
%     TableCallback(event)
%
% INPUT:
%     event: <modelit.webserver.HttpExchange>
%       with the request data and methods to generate a response.
%
% OUTPUT:
%     No output, a response with a JSON with the ag-grid example data is
%     returned to the client.
%
% EXAMPLE:
%  server = modelit.web.server.Server(8081, @TableCallback).start()
%
%  % Open a webbrowser and type: http://localhost:8081/table/index.html in the address bar

%   Copyright 2023 Modelit, www.modelit.nl

switch lower(event.getRequestMethod)
    case 'get'
        p = char(event.getPath);
        [~, ~, ext] = fileparts(p);

        if isempty(ext)
            persistent T
            if isempty(T)
                T = getData();
            end

            fields = fieldnames(T);
            props = repmat(struct('field','','filter',true,'suppressMenu',true), length(fields),1);
            for i=1:length(fields)
                props(i).field = fields{i};
            end
            event.send(200, jsonencode(struct('props', props, 'data', T)));
        else
            fname = fullfile(pwd, 'examples', 'resources', p);
            if isfile(fname)
                response = readBytesFromFile(fname); %this file needs ##readBytesFromFile##
                event.send(200, response);
                return
            else
                event.send(404);
                return
            end
        end
    otherwise
        event.send(405); % Method not allowed
        return;
end
end

%__________________________________________________________________________
function T = getData()

T = readlines(fullfile(pwd,'examples','resources','olympic-winners.json'));
T = jsondecode(T);
for i=1:length(T)
    % Correct empty age
    if isempty(T(i).age)
        T(i).age = NaN;
    end
end
end