/*
 * Author: Bubba Li
 * Created Date: 01/19/2022
 * Purpose: Utility class for describe layouts
 * Test Class: NewAndEditLeadController
 * History: 
 *      01/19/2022 - Bubba Li - Initial Code.
 * 
 * */
public without sharing class NewAndEditLeadController {
    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 = 'Lead';
    public Boolean isNewMode{set;get;}
    public String rtTypeId {get; set;}
    public String AWSDataId{set;get;}
    //fieldLabel fieldAPI
    public String fieldApiListStr {get; set;}
    public NewAndEditLeadController(ApexPages.StandardController controller) {
        isNewMode = true;
        List<String> fieldList = new List<String>(Schema.getGlobalDescribe().get('Lead').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 = '01210000000QiRa';//For testing
        layoutSections = LayoutDescriberHelper.describeSectionWithFields(rtTypeId, 'Lead','classic');
        if(obj.Id != null){
            isNewMode = false;
            Lead leadData = [select Id,RecordTypeId,AWS_Data_Id__c from Lead where id =: obj.Id];
            rtTypeId = leadData.RecordTypeId;
            AWSDataId = leadData.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 saveLead(String leadJson,String transId,Boolean isNew) {
        System.debug('Lead Info:' + JSON.serialize(leadJson));
        //1. Prepare the payload for  Lead
        Schema.SObjectType leadSchema = schemaMap.get(sobjectTypeValue);
        Map<String, Schema.SObjectField> fieldAPIToTypeMap = leadSchema.getDescribe().fields.getMap();
        Map<String,Object> fieldValueMap = (Map<String,Object>)JSON.deserializeUntyped(leadJson);
        Lead leadInfo = new Lead();
        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'){
                leadInfo.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',' ');
                    leadInfo.put(fieldAPI, Datetime.valueOfGmt(dt));
                }             
            }else if(String.valueOf(fielddataType)=='Number'||String.valueOf(fielddataType)=='DOUBLE' ){
                leadInfo.put(fieldAPI, Decimal.valueOf(String.valueOf(fieldValueMap.get(fieldAPI))));
            } else if(String.valueof(fielddataType)=='BOOLEAN'){
                leadInfo.put(fieldAPI, Boolean.valueOf(fieldValueMap.get(fieldAPI)));
            }else {
                leadInfo.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 leadInfo;
            }else{
                //Id leadIdValue = [select id from Lead where AWS_Data_Id__c =:awsId];
                leadInfo.put('Id','00Q1m000001lVY8');//For testing;
                update leadInfo;
            }
            // //saveTransLog(transId, leadInfo.AWS_Data_Id__c, status, '');
            // Transaction_Log__c traLog = new Transaction_Log__c();
            // // AWS_Data_Id__c=AWSDataId,TransId__c=transId,JsonContent__c=leadJson,Status__c=status
            // traLog.AWS_Data_Id__c = AWSDataId;
            // traLog.TransId__c = transId;
            // traLog.JsonContent__c = leadJson;
            // traLog.Status__c = status;
            // insert traLog;
            resp.recordId = leadInfo.Id;
            // resp.message = 'success saveLead';
            resp.status = status;
            return resp;

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