/***********************************************************************************************************
 * Name         : CustomPathController
 * Purpose      : Controller of customPath LWC
 **********************************************************************************************************/

public class CustomPathController {
    public static String ACTIVE_SLDS_PATH_ITEM_CLASS = 'slds-path__item slds-is-active';
    public static String INCOMPLETE_SLDS_PATH_ITEM_CLASS = 'slds-path__item slds-is-incomplete';
    public static String COMPLETE_SLDS_PATH_ITEM_CLASS = 'slds-path__item slds-is-complete';

    /**
    * @description return a list of picklist label and a respective SLDS class according to
    * past, current and remaining values
    * @param recordId id of the record identified by the LWC component
    * @param fieldName name of the picklist field
    */
    @AuraEnabled(cacheable=true)
    public static List<PathData> getPickList(String recordId, String fieldName) {
        List<Schema.SObjectType> sObjTypes = Schema.getGlobalDescribe().values();
        Map<String, String> objectMap = new Map<String, String>();

        for (Schema.SObjectType sObjType : sObjTypes) {
            objectMap.put(sObjType.getDescribe().getKeyPrefix(), sObjType.getDescribe().getName());
        }

        String prefix = recordId.left(3);
        String objectName = objectMap.get(prefix);
        String query = 'SELECT ' + fieldName + ' FROM ' + objectName + ' WHERE Id = :recordId';

        List<SObject> sObjects = Database.query(query);
        String selectedValue = String.valueOf(sObjects[0].get(fieldName));

        Schema.SObjectField sObjField = Schema.getGlobalDescribe()
            .get(objectName)
            .getDescribe()
            .fields.getMap()
            .get(fieldName);
        Schema.DescribeFieldResult fieldResult = sObjField.getDescribe();
        List<Schema.PicklistEntry> pickListEntries = fieldResult.getPicklistValues();

        Boolean currentValueMatched = false;
        List<PathData> pathDataList = new List<PathData>();

        for (Schema.PicklistEntry pickListEntry : pickListEntries) {
            PathData pathData = new PathData();
            pathData.label = pickListEntry.getLabel();

            if (pathData.label == selectedValue) {
                pathData.classValue = ACTIVE_SLDS_PATH_ITEM_CLASS;
                currentValueMatched = true;
            } else if (currentValueMatched) {
                pathData.classValue = INCOMPLETE_SLDS_PATH_ITEM_CLASS;
            } else {
                pathData.classValue = COMPLETE_SLDS_PATH_ITEM_CLASS;
            }

            pathDataList.add(pathData);
        }
        return pathDataList;
    }

    public class PathData {
        @AuraEnabled public String label;
        @AuraEnabled public String classValue;
    }
}
