/**
 * @since Last modified: 2024/04/20 14:42:05
 * @function getBetweenEls
 * @description Find the middle node from the start to the end node.
 * @param  {string} selector - Selector for the middle node.
 * @param  {string|HTMLElement} start - Selector for the start node.Usage is the same as getEl.
 * @param  {string|HTMLElement} end - Selector for the end node.Usage is the same as getEl.
 * @param  {string|HTMLElement} [parent=document.body] - Selector for the parent node.Usage is the same as getEl.
 * @returns {boolean} Return between elements.
 * @see {@link https://codepen.io/axui/pen/LYvgQEd|demo @ codepen}
 * @example
 * ax.getBetweenEls({selector:'h2',start:'#start',end:'#end'});
 * <!--return elements array-->
 */






'use strict';

import { T_el, T_sel } from "../../../types/ax";
import getEl from "./getEl";
import getEls from "./getEls";

const getBetweenEls = ({ selector, start, end, parent }: { selector: string, start: T_sel, end?: T_sel, parent?: T_sel }): T_el[] => {
    let parentEl = getEl(parent) || document.body,
        startEl = getEl(start),
        endEl = getEl(end),
        els = getEls(selector, parentEl),
        result: T_el[] = [];
    
    if (els.length === 0) { return result }
    if (startEl && !endEl) {
        
        result = els.filter((k: any) => {
            
            return (startEl as T_el).compareDocumentPosition(k) & Node.DOCUMENT_POSITION_FOLLOWING;
        });
    } else if (!startEl && endEl) {
        
        result = els.filter((k: any) => {
            
            return (endEl as T_el).compareDocumentPosition(k) & Node.DOCUMENT_POSITION_PRECEDING;
        });
    } else if (startEl && endEl) {
        result = els.filter((k: any) => {
            return ((startEl as T_el).compareDocumentPosition(k) & Node.DOCUMENT_POSITION_FOLLOWING) && (endEl as T_el).compareDocumentPosition(k) & Node.DOCUMENT_POSITION_PRECEDING;
        });
    }
    return result;
};
export default getBetweenEls;
