const FILE_URL = import.meta.env.VITE_BASE_PATH

export const imageSuffixes = ['.jpg', '.png', '.gif', '.jpeg']
export const videoSuffixes = ['.avi', '.mp4', '.mpeg', '.wmv', '.mov']
export const audioSuffixes = ['.mp3', '.wma', '.avi', '.mdi', '.rmvb', '.ogg']

export const FILETYPE = {
    IMAGE: 'IMAGE',
    VIDEO: 'VIDEO',
    AUDIO: 'AUDIO',
    OTHER: 'OTHER'
}

export function isImageByUrl(src) {
    return getFileTypeByUrl(src) === FILETYPE.IMAGE
}

export function isVideoByUrl(src) {
    return getFileTypeByUrl(src) === FILETYPE.VIDEO
}

export function isAduioByUrl(src) {
    return getFileTypeByUrl(src) === FILETYPE.AUDIO
}

export function getFullUrl(src) {
    const rx = /^https?:\/\//i
    return rx.test(src) ? src : FILE_URL + src
}

export function getFileTypeByUrl(src) {
    src = src.toLowerCase()
    const reg = /\.[^.]+$/
    const matches = reg.exec(src)
    if (matches) {
        const suffix = matches[0]
        if (imageSuffixes.includes(suffix)) return FILETYPE.IMAGE
        if (videoSuffixes.includes(suffix)) return FILETYPE.VIDEO
        if (audioSuffixes.includes(suffix)) return FILETYPE.AUDIO
    }
    return FILETYPE.OTHER
}

export function download(url, fileName) {
    const xhr = new XMLHttpRequest()
    xhr.open('get', url)
    xhr.responseType = 'blob'
    xhr.send()
    xhr.onload = function (sues) {
        const data = xhr.response
        const imgurl = URL.createObjectURL(data)
        let a = document.createElement('a')
        a.href = imgurl
        a.download = fileName || ''
        a.click()
        a = null
    }
}
