import { FileUploadModel } from '@upload-download/model/file-upload.model';
import { Dossier } from '@red/domain';

const validDocumentMimeTypes = [
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'application/pdf',
];

const validDocumentExtensions = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'];

export function isPdf(file: FileUploadModel): boolean {
    return file.file.type?.toLowerCase() === 'application/pdf' || file.file.name.toLowerCase().endsWith('.pdf');
}

export function isZip(file: FileUploadModel): boolean {
    return file.file.type?.toLowerCase() === 'application/zip' || file.file.name.toLowerCase().endsWith('.zip');
}

export function isCsv(file: FileUploadModel): boolean {
    return file.file.type?.toLowerCase() === 'text/csv' || file.file.name.toLowerCase().endsWith('.csv');
}

export function isDocument(file: FileUploadModel): boolean {
    const extension = file.file.name.toLowerCase().substring(file.file.name.toLowerCase().lastIndexOf('.') + 1);
    return validDocumentMimeTypes.includes(file.file.type?.toLowerCase()) || validDocumentExtensions.includes(extension);
}

export type Files = FileList | File[];

export function isAcceptedFileType(file: FileUploadModel): boolean {
    return isPdf(file) || isZip(file) || isDocument(file) || isCsv(file);
}

export function convertFiles(files: FileList | File[], dossier: Dossier): FileUploadModel[] {
    const uploadFiles: FileUploadModel[] = [];
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        uploadFiles.push({
            file: file,
            progress: 0,
            completed: false,
            error: null,
            dossierId: dossier.id,
            dossierName: dossier.dossierName,
            sizeError: false,
            typeError: false,
            retryCount: 0,
            size: file.size,
        });
    }

    const pdfFiles = uploadFiles.filter(file => !isCsv(file)).sort((a, b) => a.size - b.size);
    const csvFiles = uploadFiles.filter(file => isCsv(file));

    const sortedFiles = [...pdfFiles, ...csvFiles];

    console.log('[REDACTION] Uploading files: ', sortedFiles);
    return sortedFiles;
}

export function handleFileDrop(event: DragEvent, dossier: Dossier, uploadFiles: (files: FileUploadModel[]) => void) {
    event.preventDefault();
    event.stopPropagation();
    const { dataTransfer } = event;
    let files: FileList | File[] = [];
    if (dataTransfer.items) {
        for (let i = 0; i < dataTransfer.items.length; i++) {
            // If dropped items aren't files, reject them
            if (dataTransfer.items[i].kind === 'file') {
                files.push(dataTransfer.items[i].getAsFile());
            }
        }
        dataTransfer.items.clear();
    } else {
        files = dataTransfer.files;
        dataTransfer.clearData();
        uploadFiles(convertFiles(files, dossier));
    }

    const convertedFiles = convertFiles(files, dossier);
    if (convertedFiles.length > 0) {
        uploadFiles(convertedFiles);
    }
}
