% MKSApplication is a top-level class for parsing 
% an MKS JSON string into a collection of objects

% Version 2.0 - updated 2024-02-24
classdef MKSApplication < MKSBase

    % Class properties
    properties
        request MKSRequest
    end

    % Class methods
    methods

        % constructor - input type
        function mksApp = MKSApplication(input, type)

            % Dispatch on type
            switch( type )

                % MKS request filename
                case("queryfile")
                    mksApp.request = mksApp.readQueryFile(input);

                % MKS response filename
                case("filename")
                    mksApp.request = mksApp.readJsonFile(input);

                % MKS request query string
                case("query")
                    mksApp.request = mksApp.readQuery(input);
                    
                % MKS response string
                case("string")
                    mksApp.request = mksApp.readJson(input);

            end
        end

        % readQueryFile - process an MKS API JSON request
        function mksReq = readQueryFile(mksApp, fileName)

            % Prepare and process query
            urlQuery = "https://mkswebapi.com/process?request=";
            urlQuery = urlQuery + urlencode(fileread(fileName));
            response = webread(urlQuery);

            % Decode json and parse structures
            mksReq = mksApp.processJson(jsondecode(response));

        end

        % readJsonFile - process an MKS API JSON response
        function mksReq = readJsonFile(mksApp, fileName)

            % Read contents, decode, and parse structures
            jsonStruct = jsondecode(fileread(fileName));
            mksReq = mksApp.processJson(jsonStruct);

        end

        % readQuery - process an MKS API request
        function mksReq = readQuery(mksApp, jsonQuery)

            % Prepare and process query
            urlQuery = "https://mkswebapi.com/process?request=";
            urlQuery = urlQuery + urlencode(jsonQuery);
            response = webread(urlQuery);

            % Decode json and parse structures
            mksReq = mksApp.processJson(jsondecode(response));

        end

        % readJson - process an MKS API response
        function mksReq = readJson(mksApp, jsonString)

            % Decode json and parse structures
            mksReq = mksApp.processJson(jsondecode(jsonString));

        end

        % readJsonStruct
        function mksReq = processJson(~, jsonStruct)

            % Create request object
            mksReq = MKSRequest;

            % Parse input structure
            mksReq = mksReq.processJson(jsonStruct);

        end
    end
end