classdef ImportModelFromExcel < handle
    % This class read the input Excel file and returns MATLAB tables.
    
    properties
        ExcelName;
        ComponentSheetName;
        PortSheetName;
        ConnectionSheetName;
        PortInterfaceSheetName;
        RequirementLinksSheetName;

        Components;
        Ports;
        Connections;
        Interfaces;
        RequirementLinks;
    end
    
    methods
        %% Constructor function.
        function obj = ImportModelFromExcel(xlPath, compSheetName, portSheetName, conxnSheetName,portInterfaceSheetName, requirementLinksSheetName)
            % This is a constructor function to class ImportModelFromExcel.
            % This function sets up the sheet name to read for different system
            % composer model elements.
            assert(~isempty(xlPath))
            
            obj.ExcelName = xlPath;
            
            % Hierarchy Info sheet.
            obj.ComponentSheetName = compSheetName;
            
            % Ports Info sheet.
            obj.PortSheetName = portSheetName;
            
            % Connections Info sheet.
            obj.ConnectionSheetName = conxnSheetName;
            
            % Port interfaces sheet name.
            obj.PortInterfaceSheetName = portInterfaceSheetName;
            
            % Requirement links sheet name.
            obj.RequirementLinksSheetName = requirementLinksSheetName;
        end
        
        %% readTableFromExcel : Creates MATLAB tables from the Excel file.
        function readTableFromExcel(obj)
            % Function reads the Excel file and creates MATLAB tables.
            % Check if the Excel file exists
            if obj.excelFileExists()
                obj.Components = obj.readTableFromExcelImpl(obj.ComponentSheetName);
                obj.Ports = obj.readTableFromExcelImpl(obj.PortSheetName);
                obj.Connections = obj.readTableFromExcelImpl(obj.ConnectionSheetName);
                obj.Interfaces = obj.readTableFromExcelImpl(obj.PortInterfaceSheetName);
                obj.RequirementLinks = obj.readTableFromExcelImpl(obj.RequirementLinksSheetName);
            end
        end
        
        %% Utility function to check if the file exists.
        function xlExists = excelFileExists(obj)
            xlExists = (exist(obj.ExcelName,'file') == 2);
        end

        %% Impl function to read table from Excel file
        function resultTable = readTableFromExcelImpl(obj, sheetName)
            try
                resultTable = readtable(obj.ExcelName, 'Sheet', sheetName, 'ReadVariableNames', true);
            catch
                % Provided sheet name does not exist
                resultTable = table;
            end
            c = table2cell(resultTable);
            c(ismissing(resultTable)) = {''};
            resultTable = cell2table(c, 'VariableNames', resultTable.Properties.VariableNames);
        end
    end
end

