/**
 * @since Last modified: 2024-09-10 09:46:00
 * @constant fileTools
 * @description A collection of methods for operating files.
 * @property {function} download - Build a tag to download the file in the url.
 * @property {function} getBase64 - Convert file to Base64 format.Return a promise.
 * @property {function} urlToFile - Convert the URL of the remote file to file format.Return a promise.
 * @see {@link https://codepen.io/axui/pen/abXwOXm|demo @ codepen}
 */
'use strict';
import { T_fn } from "../../../types/ax";
import ax from "../ax";
import config from "../global/config";
import ajax from "./ajax";
import createEl from "./createEl";
type T_file ={
    download:any;
    getBase64:any;
    getFileName:any;
    urlToFile:any;
}
const fileTools:T_file = {
    download: (url: string, name: string) => {
        let xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = 'blob';
        xhr.onload = function () {
            let url = window.URL.createObjectURL(xhr.response),
                dom = createEl('a');
            (dom as any).src = url;
            (dom as any).download = name || config.lang.placeholder.downloadName + Date.now();
            dom.click();
        }
        xhr.send();
    },
    getBase64: (file: any, cb?: T_fn) => {
        return new Promise((resolve, reject) => {
            try {
                let reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = (e) => {
                    cb && cb(e?.target?.result);
                    resolve(e?.target?.result);
                }
            } catch (e) {
                reject(e);
            }
        });
    },
    getFileName: (url: string) => {
        try {
            return url.split('/').pop()?.trim() || '';
        } catch {
            return '';
        }
    },
    urlToFile: function (url: string, cb?: any) {
        let name = this.getFileName(url) || config.lang.placeholder.fileName + Date.now();
        return new Promise((resolve, reject) => {
            ajax({
                url: url,
                respType: 'blob',
                headers: { 'Accept': '' },
                type: 'post',
                error: (res: any) => {
                    reject(res.content);
                },
                success: (res: any) => {
                    let file = new File([res.content], name, { type: res.content.type });
                    cb && cb(file);
                    resolve(file);
                }
            });
        });
    }
};
export default fileTools;
