%Class to denote the spreadsheet widget 
%The spreadsheet widget is comprised of port names

classdef PhysmodSpreadSheet < handle

%   Copyright 2018-2020 The MathWorks, Inc.

   properties
   
       mSelectedPortNumber;
       mDialog;
       mBlockHandle;
       mData;
       mHierStrings;
   end    

   methods 
           
       function obj = PhysmodSpreadSheet(dlgSource, blkHandle,~)
            obj.mSelectedPortNumber = 1;
            obj.mDialog = dlgSource;
            obj.mBlockHandle = blkHandle;           
            obj.mData = []; 
            
            if ~isfield(obj.mDialog.UserData,'m_Children')
                obj.mDialog.UserData.m_Children = [];
            end            
            obj.mHierStrings = get_param(obj.mBlockHandle,'hierStrings');
            obj.mHierStrings = strsplit(obj.mHierStrings,';');
       end            
           
       %This function is called while rendering the spreadsheet with its
       %contents
       function children = getChildren(obj)
           
           %If 'shouldCreateSpreadsheet' is set to true then reconstruct
           %children, otherwise reuse cached spreadsheet from UserData.
           if ~isfield(obj.mDialog.UserData,'shouldRecreateSpreadsheet') ||  (obj.mDialog.UserData.shouldRecreateSpreadsheet)
              obj.mDialog.UserData.m_Children = [];
           end
           
           if isempty(obj.mDialog.UserData.m_Children)                
               children = PhysmodSpreadsheetRow.empty;
               
               count = numel(obj.mHierStrings);
               %populating the spreadsheet with port names
               for i = 1:count
                   portName = sprintf(obj.mHierStrings{i});
                   %populating each row of the spreadsheet with a spreadsheet
                   %row object
                   children(i) = PhysmodSpreadsheetRow(i,portName,obj.mBlockHandle,obj.mDialog); 
               end
               %copying the spreadsheet contents and storing them in the dialog
               %for rendering.
               obj.mDialog.UserData.m_Children = children;               
           else                
               children = obj.mDialog.UserData.m_Children;
           end
           
           %Setting flag to true.
           obj.mDialog.UserData.shouldRecreateSpreadsheet = true;
       end   
     
   end
     
end
