/*
 * Author: Bubba Li
 * Created Date: 02/08/2022
 * Purpose: Utility class for describe layouts
 * Test Class: NewAndEditAddressController
 * History: 
 *      02/08/2022 - Bubba Li - Initial Code.
 * 
 * */
public without sharing class NewAndEditAddressController {
    public List <LayoutDescriberHelper.LayoutSection > layoutSections{set;get;}
    public String awsToken{set;get;}
    public static Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    public static String sobjectTypeValue = 'Address__c';
    public Boolean isNewMode{set;get;}
    public String rtTypeId {get; set;}
    public String AWSDataId{set;get;}
    //fieldLabel fieldAPI
    public String fieldApiListStr {get; set;}
    public NewAndEditAddressController(ApexPages.StandardController controller) {
        isNewMode = true;
        List<String> fieldList = new List<String>(Schema.getGlobalDescribe().get('Address__c').getDescribe().fields.getMap().keyset());  
        // Add fields to controller. This is to avoid the SOQL error in visualforce page
        controller.addFields(fieldList);
        SObject obj = controller.getRecord();
        rtTypeId = ApexPages.currentPage().getParameters().get('RecordType');
        rtTypeId = '0121m000000kiMxAAI';//For testing
        layoutSections = LayoutDescriberHelper.describeSectionWithFields(rtTypeId, 'Address__c','classic');
        if(obj.Id != null){
            isNewMode = false;
            Address__c addressData = [select Id, RecordTypeId, AWS_Data_Id__c from Address__c where id =: obj.Id];
            rtTypeId = addressData.RecordTypeId;
            AWSDataId = addressData.AWS_Data_Id__c;
        }
        List<String> fieldApiList = new List<String>(); 
        for (LayoutDescriberHelper.LayoutSection ls : layoutSections) {
            for (LayoutDescriberHelper.LayoutField lf : ls.layoutFields) {
                if (lf.fieldAPI != '') {
                    fieldApiList.add(lf.fieldAPI);
                }
            }
        }
        fieldApiListStr = JSON.serialize(fieldApiList);
        awsToken = AWSServiceTool.getAWSToken();
    }

    public class Response{
        public String recordId{set;get;}
        public String message{set;get;}
        public String status{set;get;}
    }

    @RemoteAction
    public static Response saveAddress(String addressJson,String transId,Boolean isNew) {
        System.debug('Address Info:' + JSON.serialize(addressJson));
        //1. Prepare the payload for  Address
        Schema.SObjectType addressSchema = schemaMap.get(sobjectTypeValue);
        Map<String, Schema.SObjectField> fieldAPIToTypeMap = addressSchema.getDescribe().fields.getMap();
        Map<String,Object> fieldValueMap = (Map<String,Object>)JSON.deserializeUntyped(addressJson);
        Address__c addressInfo = new Address__c();
        for (String fieldAPI: fieldValueMap.keySet()) {
            Schema.DisplayType fielddataType = fieldAPIToTypeMap.get(fieldAPI).getDescribe().getType();  
            String fieldValue = String.valueOf(fieldValueMap.get(fieldAPI)); 
            if(String.isBlank(fieldValue)){
                continue;
            }
            if(String.valueOf(fielddataType)=='DATE'){
                addressInfo.put(fieldAPI, Date.valueOf(String.valueOf(fieldValueMap.get(fieldAPI)).replace('/', '-')));
            }else if(String.valueOf(fielddataType)=='DATETIME'){
                String dt = String.valueOf(fieldValueMap.get(fieldAPI));
                if(String.isNotBlank(dt)&&dt.contains('T')){
                    dt = dt.replace('T',' ');
                    addressInfo.put(fieldAPI, Datetime.valueOfGmt(dt));
                }             
            }else if(String.valueOf(fielddataType)=='Number'||String.valueOf(fielddataType)=='DOUBLE' ){
                addressInfo.put(fieldAPI, Decimal.valueOf(String.valueOf(fieldValueMap.get(fieldAPI))));
            } else if(String.valueof(fielddataType)=='BOOLEAN'){
                addressInfo.put(fieldAPI, Boolean.valueOf(fieldValueMap.get(fieldAPI)));
            }else {
                addressInfo.put(fieldAPI, String.valueOf(fieldValueMap.get(fieldAPI)));
            }                  
        }
        
        //2. Save Record Process
        String status = 'success';    
        Response resp = new Response();
        Savepoint sp = Database.setSavepoint();
        try{
            if(isNew){
                insert addressInfo;
            }else{
                //Id addressIdValue = [select id from Address where AWS_Data_Id__c =:awsId];
                addressInfo.put('Id','a4R1m000000KGxSEAW');//For testing;
                update addressInfo;
            }
            // //saveTransLog(transId, addressInfo.AWS_Data_Id__c, status, '');
            // Transaction_Log__c traLog = new Transaction_Log__c();
            // // AWS_Data_Id__c=AWSDataId,TransId__c=transId,JsonContent__c=addressJson,Status__c=status
            // traLog.AWS_Data_Id__c = AWSDataId;
            // traLog.TransId__c = transId;
            // traLog.JsonContent__c = addressJson;
            // traLog.Status__c = status;
            // insert traLog;
            resp.recordId = addressInfo.Id;
            // resp.message = 'success saveAddress';
            resp.status = status;
            return resp;

        } catch(Exception e) {
            Database.rollback(sp);
            // status = 'fail';
            // //saveTransLog(transId, addressInfo.AWS_Data_Id__c, status, '');
            // system.System.debug(e.getMessage() + '-' + e.getStackTraceString() + '-' + e.getLineNumber()); 
            // resp.message = e.getMessage();
            // resp.recordId = 'fail saveAddress';
            resp.status = status;
            return resp;
        }
    }
}