/**
 * @since Last modified: 2024-01-20 13:44:26
 * @function convertByte
 * @description Byte converter.Convert byte to B/KB/MB/GB/TB.
 * @param {object} [options={}]  - Parameters.
 * @param {string|number} [options.val]  - A positive integer.
 * @param {null | '' | 'B' | 'KB' | 'MB' | 'GB' | 'TB'} [options.to='']  - The specify units for conversion.
 * @param {number} [options.places=2]  - Keep decimal places after converting units.
 * @param {string} [options.outer="span"]  - The node name of outer box.
 * @param {string} [options.inner="i"]  - The node name of inner box.
 * @param {array} [options.units=['B','KB','MB','GB','TB']]  - The default units.
 * @returns {object} Return object,that contains "val" , "unit" and "str" properties.
 * @see {@link https://codepen.io/axui/pen/GReNPGb|demo @ codepen}
 * @example
 * ax.convertByte({val:12563});
 * <!--return {val:12.56,unit:'KB',str:'<span><i>12.56</i>KB</span>'-->
 */
'use strict';
import { T_obj } from '../../../types/ax';
import clampVal from './clampVal';
import toNumber from './toNumber';
type Options = {
    val: string | number;
    to: null | '' | 'B' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB';
    places: number;
    outer?: string;
    inner?: string;
    units?: string[];
}
const convertByte = ({ val, to = '', places = 2, outer = 'span', inner = 'i', units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] }: Options): T_obj => {
    val = clampVal({ val, min: 0, max: '' });
    let lvs = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'],
        unit = '',
        lv = 0,
        base = val / 1024,
        getVal = (i: number) => i === 0 ? val : (toNumber((val as number) / (1024 ** i), { places }) as number);
    if (lvs.includes((to as any))) {
        lv = lvs.findIndex(k => k === to);
    } else {
        lv = (base >= 1024 ** 4) ? 5 :
            (base >= 1024 ** 3) ? 4 :
                (base >= 1024 ** 2) ? 3 :
                    (base >= 1024) ? 2 :
                        (base >= 1) ? 1 : 0;
    }
    val = getVal(lv);
    unit = units[lv];
    return { val, unit, str: `<${outer}><${inner}>${val}</${inner}>${unit}</${outer}>` };
}
export default convertByte;
