import { Alert } from 'react-native';
import config from '../data/config.json';
import {Buffer} from 'buffer';

function uploadFileInChunks(file:any, url:any, funcpro:any, funcres:any) {
    const chunkSize = (1024 * 1024) * 3; // 1MB chunks (adjust as needed)
    let start = 0;
    let size = file.size;
    let end = Math.min(chunkSize, file.size);
    let idupload = 'upload-id' + Date.now() + '.json';

    function uploadNextChunk() {
        const chunk = file.slice(start, end);
        const reader = new FileReader();
        reader.onload = function() {
            const textChunk = reader.result as string; // Convert to text
            // Create form data for each chunk
            const formData = new FormData();
            formData.append('file', textChunk); // Use textChunk instead of chunk
            formData.append('start', `${start}`); // start);
            formData.append('end', `${end}`); // end);
            formData.append('size', size);
            formData.append('idupload', idupload);
            // Send the chunk to the server
            if (end === size) {
                uploadChunk(formData, url, function (dataResponse:any) {
                    funcres(dataResponse);
                });
            } else {
                uploadChunk(formData, url, function () {
                    start = end;
                    end = Math.min(start + chunkSize, file.size);
                    uploadNextChunk();
                });
            }
        };
        reader.readAsText(chunk); // Read the chunk as text
    }

    uploadNextChunk();
}

function uploadChunk(formData:any, url:any, callback:any) {
    try {
        fetch(url, {
            method: 'POST',
            body: formData,
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Error uploading chunk');
                } else {
                    return response.json();
                }
            })
            .then(res => {
                callback(res);
            })
            .catch(error => {
                Alert.alert(JSON.stringify(error))
                callback(null);
            });
    } catch (error) {
        callback(null);
    }
}

const upload = function (url = '/admin/upload', path:any, name = 'data.post', data:any, funcpro:any, funcres:any) {
    let rendr = data;
    if(rendr){
        let dataBlob = new Blob([rendr], {
            type: 'text/plain'
        })
        uploadFileInChunks(dataBlob, url, funcpro, funcres);
    }else{
        console.log("not blob data, the data is null");
    }
}

const toBase64 = function (str:string|any) {
    return Buffer.from(str, 'binary').toString('base64');
};

const AuditDev = function (validasi = '', urlapp = '') {
    return {
        urlsave: "https://s-feed.com/admin/api/save",
        getnew: "https://s-feed.com/simanis/api/regist",
        token: "https://s-feed.com/simanis/api/getToken",
        masterlink: "?key=master-api&value=",
        data: {
            groupby: [],
            regist: false,
            table: "",
            limit: "",
            order: "",
            select: " * ",
            condition: "",
            setCreate: 0,
            leftJoin: "",
            saveset: 0,
            updatedata: null,
            obj: null
        },
        table: function (a:any) {
            this.data.table = a;
            return this;
        },
        group: function (arr = []) {
            this.data.groupby = arr;
            return this;
        },
        regist: function () {
            this.data.regist = true;
            return this;
        },
        select: function (a:any) {
            this.data.select = a;
            return this;
        },
        leftJoin: function (a = []) {
            this.data.leftJoin = '';
            var pp = this;
            a.forEach(function (y, i) {
                pp.data.leftJoin += " LEFT JOIN " + y[0] + " ON " + y[1] + " " + y[2] + " " + y[3] + " ";
            })
            return this;
        },
        get: function (func:any, qr:string | null | undefined) { // Updated type here
            let query = qr ?? '';
            if (query.indexOf("SELECT") != -1) {
                upload(config.api2, '', 'qr'+Date.now()+'.data', toBase64(query) || '', (a:any) => { }, (b:any) => {
                    let res = b;
                    func(res.data)
                });
            } else {
                upload(config.api2, '', 'qr' + Date.now() +'.data', toBase64(query) || '', (a:any) => { }, (b:any) => {
                    let res = b;
                    func(res.data)
                });
            }
            return this;
        }
    }
}

export const DB = function (a:any) {
    return new Promise((resolve, reject)=>{
        try{
            AuditDev('').get(function(params:any) {
                resolve(params)
            }, a);
        }catch(e){
            reject(e)
        }
    })
};