/**
 * @since Last modified: 2024/06/25 10:04:19
 * @function findItem
 * @description Operate on the ax propperty of the node.
 * @param {number|string|HTMLElement|object} val  - Find item's search value.
 * @param {object[]} source  - Data sources.
 * @returns {undefined|object} - Return the search result.
 * @see {@link https://codepen.io/axui/pen/QWPdyNg|demo @ codepen}
 * @example
 * ax.findItem(0,[{a:0},{b:1}]);
 * <!--return {a:0}-->
 */




'use strict';
import { T_obj } from '../../../types/ax';
import { T_find_item } from '../../../types/utils';
import getDataType from './getDataType';
import isNull from './isNull';

const findItem = (val: T_find_item, source: T_obj[], key?: string): T_obj | undefined => {
    let valType = getDataType(val),
        result: T_obj | undefined,
        first = source[0],
        firstId = first?.id,
        idType = getDataType(firstId);
    if (isNull(firstId) && valType === 'Number') {
        
        result = source[val];
    } else {
        if (key) {
            
            result = source.find((k: T_obj) => k[key] === val);
        } else {
            
            let prop = (valType === 'Number') ? 'id' :
                
                (valType === 'String') ? (idType === 'String' ? 'id' : 'label') :
                    
                    valType.includes('HTML') ? (first.hasOwnProperty('headEl') ? 'headEl' : 'wrapEl') : '';
            if (valType === 'Object') {
                result = source.find((k: T_obj) => k === val);
            } else {
                result = prop ? source.find((k: T_obj) => k[prop] === val) : undefined;
            }
        }
    }

    return result;
}
export default findItem;
