public with sharing class SearchContactForAgencyOppController {
    public String accountId{set;get;}
    public String searchKeyWord{set;get;}
    public String staticResource {get; set;}
    public String ObjectTypeLabel {get; set;}
    public String contactAWSIds {set;get;}
    public String domId {set;get;}
    
    public SearchContactForAgencyOppController() {
        accountId = ApexPages.currentPage().getParameters().get('hosId');
        searchKeyWord = ApexPages.currentPage().getParameters().get('keyword');
        domId = ApexPages.currentPage().getParameters().get('domId');
        ObjectTypeLabel = Schema.getGlobalDescribe().get('Agency_Contact__c').getDescribe().getLabel();
        staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('Agency_Contact__c'));
        List<Agency_Contact__c> conList = [SELECT Id,Name,AWS_Data_Id__c,Hospital_Name__c,Type__c,Doctor_Division1__c FROM Agency_Contact__c WHERE Agency_Hospital__c = :accountId];
        List<String> conAWSIds = new List<String>();
        for(Agency_Contact__c con:conList){
            conAWSIds.add(con.AWS_Data_Id__c);
        }
        contactAWSIds = JSON.serialize(conAWSIds);
    }

    @RemoteAction
    public static List<Agency_Contact__c> searchContacts(String awsResult,String keyword,String hosId) {
        if(String.isBlank(keyword)){
            return null;
        }
        List<AwsData> awsData = new List<AwsData>();
        Map<String,AwsData> awsIdMap = new Map<String,AwsData>();
        if(String.isNotBlank(awsResult)){
            awsData = (List<AwsData>)JSON.deserialize(awsResult,List<AwsData>.class);
            if(awsData == null || awsData.size() == 0){
                return null;
            }
            for(AwsData cus : awsData){
                awsIdMap.put(cus.dataId,cus);
            }
        }
        
        List<Agency_Contact__c> conList = [SELECT Id,Name,AWS_Data_Id__c,Hospital_Name__c,Type__c,Doctor_Division1__c FROM Agency_Contact__c WHERE AWS_Data_Id__c IN :awsIdMap.keySet() AND Agency_Hospital__c = :hosId];
        for(Agency_Contact__c con : conList){
            con.Name = awsIdMap.get(con.AWS_Data_Id__c).name;
            con.Type__c = awsIdMap.get(con.AWS_Data_Id__c).type;
            con.Doctor_Division1__c = awsIdMap.get(con.AWS_Data_Id__c).doctorDivision1;
        }
        //get Contact No PI
        List<Agency_Contact__c> conListNoPi = [SELECT Id,Name,Hospital_Name__c,Type__c,Doctor_Division1__c FROM Agency_Contact__c WHERE Name LIKE :keyword];
        conList.addAll(conListNoPi);
        return conList;
    }

    public class AwsData{
        public String dataId{set;get;}
        public String name{set;get;}
        public String sfRecordId{set;get;}
        public String type{set;get;}
        public String doctorDivision1{set;get;}
    }
}