function sc = findElectromagneticSource(self,regionInfo)
% findElectromagneticSource - Find electromagnetic source assigned to specified geometric region
% EMS = findElectromagneticSource(SR,REGIONTYPE, REGIONID) returns the
% ElectromagneticSourceAssignment object, EMA, assigned to the given
% REGIONTYPE and REGIONID. Here, SR is the Sources property of the
% ElectromagneticModel object, REGIONTYPE is 'Face' for a 2-D model or
% 'Cell' for a 3-D model, and REGIONID is the ID of the geometric entity.
%
% % Example: Find electromagnetic source assigned to a 2-D geometry.
%
% % Create an ElectromagneticModel object and include a geometry
% model = createpde('electromagnetic','magnetostatic');
% geometryFromEdges(model,@lshapeg);
% pdegplot(model,'EdgeLabels','on')
%
% % Assign different values of relative permeability to different faces.
% electromagneticSource(model,'Face',1,'CurrentDensity',10);
% electromagneticSource(model,'Face',2,'CurrentDensity',20);
% electromagneticSource(model,'Face',3,'CurrentDensity',30);
%
% % Check the electromagnetic source specification for face 2.
% sF2= findElectromagneticSource(model.Sources,'Face',2)
%
%    See also pde.ElectromagneticModel/electromagneticSource

% Copyright 2020-2021 The MathWorks, Inc.

arguments
    self pde.ElectromagneticSourceAssignmentRecords
    regionInfo.Face
    regionInfo.Cell
end

narginchk(3,3);

if isempty(self.ParentModel.Geometry)
    sc = pde.ElectromagneticSourceAssignment.empty;
    return;
end

validDomain = self.ParentModel.validDomain;
maxDomainID = self.ParentModel.maxDomainID;

if ~isfield(regionInfo,validDomain)
    error(message('pde:ElectromagneticModel:invalidSourceQuery'));
end

queryRegionID = regionInfo.(validDomain);
if any(queryRegionID > maxDomainID)
    error(message('pde:materialPropertySpecification:invalidRegionID'));
end

numassigns = numel(self.SourceAssignments);
numqueries = numel(queryRegionID);

% Check homogeneity of output for all query regions, all valid records or all empty. 
% Error if only a subset of query region IDs has valid assignment.
regionsWithAssignment = [self.SourceAssignments.RegionID];
numQueryRegionsWithAssignment = nnz(intersect(regionsWithAssignment,queryRegionID));
allQueryRegionsHaveAssignment = numQueryRegionsWithAssignment == numqueries;
if ~allQueryRegionsHaveAssignment && (numQueryRegionsWithAssignment > 0)
    error(message('pde:ElectromagneticModel:queryOnUnassignedRegions'));
end

sc = pde.ElectromagneticSourceAssignment.empty(0,numel(queryRegionID));
for i = 1:numqueries
    rid = queryRegionID(i);
    for j = numassigns:-1:1
       thisca =  self.SourceAssignments(j);
       if strcmp(validDomain,thisca.RegionType) && ismember(rid, thisca.RegionID)
          sc(i) = thisca;
          break
       end
    end
end
end
