import { $t } from '@/locales'

/**
 * Transform record to option
 *
 * @example
 *   ```ts
 *   const record = {
 *     key1: 'label1',
 *     key2: 'label2'
 *   };
 *   const options = transformRecordToOption(record);
 *   // [
 *   //   { value: 'key1', label: 'label1' },
 *   //   { value: 'key2', label: 'label2' }
 *   // ]
 *   ```;
 *
 * @param record
 */
export function transformRecordToOption<T extends Record<string, string>>(record: T) {
  return Object.entries(record).map(([value, label]) => ({
    value,
    label,
  })) as CommonType.Option<keyof T, T[keyof T]>[]
}

/**
 * Translate options
 *
 * @param options
 */
export function translateOptions(options: CommonType.Option<string, App.I18n.I18nKey>[]) {
  return options.map(option => ({
    ...option,
    label: $t(option.label),
  }))
}

/**
 * Toggle html class
 *
 * @param className
 */
export function toggleHtmlClass(className: string) {
  function add() {
    document.documentElement.classList.add(className)
  }

  function remove() {
    document.documentElement.classList.remove(className)
  }

  return {
    add,
    remove,
  }
}

/**
 * Join path segments
 * @param paths
 */
export function browserPathJoin(...paths: string[]) {
  return paths.join('/').replace(/\/+/g, '/')
}

/**
 * 版本比较
 * @param v1 
 * @param v2 
 * @param separator 分隔符 默认.
 * @returns 1 v1>v2 | -1 v1<v2 | 0 v1==v2
 */
export function compareVersion(v1: string, v2: string, separator = '.') {
  const s1 = v1.split(separator)
  const s2 = v2.split(separator)
  const len = Math.max(s1.length, s2.length)
  
  for (let i = 0; i < len; i++) {
    const num1 = parseInt(s1[i] || '0')
    const num2 = parseInt(s2[i] || '0')
    if (num1 > num2) return 1
    if (num1 < num2) return -1
  }
  return 0
}
