function TemperatureConversionCallback(event)
% TemperatureConversionCallback - Callback called by
% modelit.webserver.Server object for converting Celcius to Fahrenheit and
% vice versa. This example serves the HTML page to the client and uses
% JavaScript to update the components of the HTML page. The server only
% processes requests to calculate the conversion.
%
% CALL:
%     TemperatureConversionCallback(event)
%
% INPUT:
%     event: <modelit.webserver.HttpExchange>
%       with the request data and methods to generate a response.
%
% OUTPUT:
%     No output, a response with a JSON object is return to the client.
%
% EXAMPLE:
%  server = modelit.web.server.Server(8081, @TemperatureConversionCallback).start()
%
%  % Open a webbrowser and type: http://localhost:8081/ in the address bar

%   Copyright 2023 Modelit, www.modelit.nl

switch lower(event.getRequestMethod)
    case 'get'
        fname = fullfile(pwd, 'examples', 'resources', 'temperatureconversion.html');
        if exist(fname, 'file')
            response = readBytesFromFile(fname); %this file needs ##readBytesFromFile##
            event.send(200, response);
            return
        else
            event.send(404);
            return
        end

    case 'post'
        response = process(event);
        % Set the MIME type and allow Cross Origin Resource Sharing
        event.addResponseHeader('Content-Type', 'application/json',...
            'Access-Control-Allow-Origin', '*');

        % Send the response back to the client
        event.send(200, response);
        return;
    otherwise
        event.send(405); % Method not allowed
        return;
end

%__________________________________________________________________________
function text = process(event)
% process - Do the conversion.
%
% CALL:
%  text = process(event)
%
% INPUT:
%  event: <modelit.web.server.HttpExchange>
%
% OUTPUT:
%  text: <string>
%    json string with data for the front-end.

% Make a simple JSON object with Matlab method
input = jsondecode(char(event.getRequestBody)');

S = struct('celcius',NaN,'fahrenheit',NaN);

try
    if isfield(input, 'celcius')
        % celcius given, calculate fahrenheit
        S = struct('celcius', input.celcius, 'fahrenheit', input.celcius*1.8 + 32);
    elseif isfield(input, 'fahrenheit')
        % fahrenheit given, calculate celcius
        S = struct('celcius',(input.fahrenheit - 32)/1.8,'fahrenheit', input.fahrenheit);
    end
catch me
end

text = jsonencode(S);