import { LexoRank } from "lexorank";

export function getNewLexorank(
    left?: LexoRank | null,
    right?: LexoRank | null
): LexoRank {
    if (right) {
        if (left) return left?.between(right);
        return right.between(LexoRank.min());
    }
    if (left) {
        return left.between(LexoRank.max());
    }
    return LexoRank.middle();
}

export const getNewDndLexorank = <T>(
    sourceIdx: number,
    targetIdx: number,
    items: T[],
    key: keyof T
): string => {
    let leftIndex = targetIdx;
    let rightIndex = targetIdx + 1;
    if (targetIdx < sourceIdx) {
        leftIndex = targetIdx - 1;
        rightIndex = targetIdx;
    }

    const leftLexorank: LexoRank | null =
        leftIndex >= 0 ? LexoRank.parse(items[leftIndex][key] as string) : null;
    const rightLexorank: LexoRank | null =
        rightIndex < items.length
            ? LexoRank.parse(items[rightIndex][key] as string)
            : null;

    return getNewLexorank(leftLexorank, rightLexorank).toString();
};
