import * as riot from 'riot'

import TinyLoading from '@tiny-components/loading/src/loading.riot'
import TinySidebarFormHeader from './forms/header.riot'
import TinySidebarFormFooter from './forms/footer.riot'
import TinyNotification from '@tiny-components/notification/src/notification.riot'

import FieldError from '@tiny-components/validator/src/fieldError.riot'

import potatoAppsView from './views/apps.riot'
import potatoFieldTags from './components/fields/tags.riot'
import potatoCloseButton from './components/closeButton.riot'

// register & mount riot component
riot.register('field-error', FieldError)

riot.register('tiny-loading', TinyLoading)
riot.register('tiny-sidebar-form-header', TinySidebarFormHeader)
riot.register('tiny-sidebar-form-footer', TinySidebarFormFooter)
riot.register('tiny-notification', TinyNotification)

riot.register('potato-field-tags', potatoFieldTags)
riot.register('potato-apps-view', potatoAppsView)
riot.register('potato-close-button', potatoCloseButton)

// adding events for Neutralino
Neutralino.events.on('ready', async () => {

    // @TODO thats mad, it is only a workaround, don't judge me, i will do better
    // its no possible to create a hole path, solving this with array and a recursive function
    try {
        const result = await Neutralino.filesystem.getStats('./.storage')

        if (result) {
            try {
                await Neutralino.filesystem.createDirectory('./.storage/pouchdb')
            } catch(error) {

            }
        }
    } catch(error) {
        if (error.code === 'NE_FS_NOPATHE') {
            try {
                await Neutralino.filesystem.createDirectory('./.storage')
                await Neutralino.filesystem.createDirectory('./.storage/pouchdb')
            } catch(error) {

            }
        }
    }

    riot.mount('potato-apps-view')
    riot.mount('tiny-notification')
})

// let it rain
Neutralino.init()

// workaround to prevent a stack overflow
window._arrayBufferToBase64 = function _arrayBufferToBase64(buffer) {
    var binary = '';

    var bytes = new Uint8Array(buffer);
    var len = bytes.byteLength;

    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }

    return window.btoa(binary);
}