export const sdcard = navigator.getDeviceStorage('sdcard')

export function promisify(request) {
    return new Promise((resolve, reject) => {
        request.onsuccess = (event) => {
            resolve(request.result)
        }
        request.onerror = (event) => {
            reject(request.error)
            console.error(request.error)
        }
    })
}

export function joinPath(left, right) {
    return (left + right).replaceAll(/\/{2,}/g, '/')
}

function handle(sPath, sName) {
    return {
        name: sName,
        path: sPath,
        kind: 'directory'
    }
}

function resolveHandle(handle) {
    let cs = handle.path.split('/')
    let f = filesystemIndex

    for(let c of cs) {
        f = f.entries[c]
        if(f == undefined) {
            throw new Error('Invalid path:', handle.path)
        }
    }

    return f
}

export let filesystemIndex

export function Start() {
    
}

export const createIndex = () => {
    return new Promise(filesystemIndexHandler)
}

const filesystemIndexHandler = (resolve, reject) => {
    let cursor = sdcard.enumerate();
    filesystemIndex = {}
    
    cursor.onerror = function() {
        reject(cursor.error)
    }
    cursor.onsuccess = function() {
        if(!this.result) {
            return resolve(filesystemIndex)
        }
        let cs = this.result.name.split('/').slice(1)
        let f = filesystemIndex
        let c
        for(let i = 0; i < cs.length; i++) {
            c = cs[i]
            if(!f.entries) {
                f.kind = 'directory'
                f.entries = {}
            }
            f = f.entries[c] ??= handle('/' + cs.slice(0, i + 1).join('/'), c)
        }
        f.kind = 'file'
        // f.file = this.result

        this.continue()
    }
}

export async function Entries(handle) {
    if(!filesystemIndex)
        await createIndex()
    let pool = new Map()
    let t = handle == null ? filesystemIndex : handle
    for(let n in t.entries ?? {}) {
        let h = t.entries[n]
        pool.set(h.name, h)
    }

    return pool
}

export function Open(hFile) {
    // return hFile.file
    return promisify(sdcard.get(hFile.path))
}