const { DistributionAPI } = require('helios-core/common')

const ConfigManager = require('./configmanager')

const DEFAULT_REMOTE_DISTRO_URL = 'https://cdn.mysticred.space/launcher/distribution.json'

let remoteDistroUrl = DEFAULT_REMOTE_DISTRO_URL
let activeApi = createApi(remoteDistroUrl)

function createApi(url) {
    const api = new DistributionAPI(
        ConfigManager.getLauncherDirectory(),
        null,
        null,
        url,
        false
    )

    return api
}

function replaceApi(url) {
    const nextApi = createApi(url)

    if(activeApi != null){
        if(typeof activeApi.commonDir !== 'undefined'){
            nextApi.commonDir = activeApi.commonDir
        }
        if(typeof activeApi.instanceDir !== 'undefined'){
            nextApi.instanceDir = activeApi.instanceDir
        }
        if(typeof activeApi.isDevMode === 'function' && activeApi.isDevMode()){
            nextApi.toggleDevMode(true)
        }
    }

    activeApi = nextApi
    remoteDistroUrl = url
}

exports.DEFAULT_REMOTE_DISTRO_URL = DEFAULT_REMOTE_DISTRO_URL

exports.getRemoteDistributionUrl = function() {
    return remoteDistroUrl
}

exports.setRemoteDistributionUrl = function(url) {
    if(url != null && url.trim().length > 0 && url !== remoteDistroUrl){
        replaceApi(url)
    }
    return remoteDistroUrl
}

exports.resetRemoteDistributionUrl = function() {
    replaceApi(DEFAULT_REMOTE_DISTRO_URL)
    return remoteDistroUrl
}

exports.DistroAPI = new Proxy({}, {
    get(_target, prop) {
        const value = activeApi[prop]
        if(typeof value === 'function'){
            return value.bind(activeApi)
        }
        return value
    },
    set(_target, prop, value) {
        activeApi[prop] = value
        return true
    },
    has(_target, prop) {
        return prop in activeApi
    }
})
