/**
 * @since Last modified: 2024/03/19 23:01:30
 * @function moveItem
 * @description Flattens the index position of an item in an array..
 * @param {object} options - Parameters.
 * @param {any} options.source - The item to be flattened.
 * @param {any} options.target - The item that was moved here.
 * @param {any[]} options.data - Data source array.
 * @param {boolean} [options.isFront=true] - Insert in front of or behind the target object.
 * @returns  null.
 * @see {@link https://codepen.io/axui/pen/yLrJjgZ|demo @ codepen}
 * @example
 * ax.moveItem({source:0,target:2,data:['a','b','c','d','e']});
 * <!--['a','b','c','d','e']=>['b','a','c','d','e']-->
 */






'use strict';
import getDataType from './getDataType';
import isEmpty from './isEmpty';
import isNull from './isNull';
const moveItem = ({ source, target, data, isFront = true }: { source: any, target?: any, data: any[], isFront?: boolean }) => {
    let sourceType = getDataType(source),
        targetType = getDataType(target),
        from: number = (sourceType === 'Number') ? source : data.indexOf(source),
        to: number = (targetType === 'Number') ? target : data.indexOf(target),
        sourceObj = sourceType === 'Number' ? data[source] : source,
        offset = isFront ? 0 : 1;

    
    if (isNull(from) || isEmpty(data)) {
        throw new Error('Cannot get the index of the moving item!');
    }
    
    if (from > data.length || from < 0) {
        throw new Error('Exceeded array length!');
    }
    
    if (to < 0 || to > data.length) {
        to = isFront ? 0 : data.length - 1;
    }
    
    if (from === to) {
        console.warn('Source and target are the same, not moved!');
        return;
    }
    
    data.splice(from, 1);
    
    from < to ? to-- : null;
    
    data.splice(to + offset, 0, sourceObj);
}
export default moveItem;
