import {Session} from './Session.service.js'
import {Resource} from '../Resource.js'
import {Message} from './Message.service.js'

export class ActionService {
    static get() {
        if ( !this.instance ) {
            this.instance = new ActionService()
        }

        return this.instance
    }

    async perform(action, data, onComplete = () => {}) {
        if ( action.type === 'back' ) this.goBack()
        if ( action.type === 'resource' ) await this.handleResourceAction(action, data, onComplete)
        if ( action.type === 'route' ) await this.handleRouteAction(action, data, onComplete)
    }

    async handleResourceAction(action, data, onComplete) {
        const resource = await Resource.get(action.resource)
        if ( action.action === 'insert' ) this.launchResourceForm(action.resource)
        if ( action.action === 'update' ) this.launchResourceForm(action.resource, data[resource.configuration.primaryKey])
        if ( action.action === 'list' ) this.launchResourceListing(action.resource)
        if ( action.action === 'view' ) this.launchResourceForm(action.resource, data[resource.configuration.primaryKey], true)
        if ( action.action === 'delete' ) {
            await Message.get()
                .modal({
                    title: `Delete ${resource.singular()}?`,
                    message: `Are you sure you want to delete this ${resource.singular().toLowerCase()}? This action cannot be undone.`,
                    buttons: [
                        {
                            type: 'close',
                            text: 'Keep it',
                        },
                        {
                            class: ['btn', 'btn-danger'],
                            type: 'close',
                            text: 'Delete it',
                            onClick: async () => {
                                await resource.delete(data[resource.configuration.primaryKey])
                                await Message.get()
                                    .alert({
                                        message: `The ${resource.singular().toLowerCase()} was deleted successfully.`,
                                        timeout: 7000,
                                    })

                                await onComplete()
                            },
                        }
                    ],
                })
        }
    }

    launchResourceListing(key) {
        location.assign(Session.get().url(`dash/cobalt/listing/${key}`))
    }

    launchResourceForm(key, id, view = false) {
        location.assign(Session.get().url(`dash/cobalt/form/${key}${id ? '/' + id : ''}${view ? '/view' : ''}`))
    }

    async handleRouteAction(action, data, onComplete = () => {}) {
        let route = Session.get().url(action.route)
        route = this.replacePlaceholders(route, { resourceKey: action.resource })
        route = this.replacePlaceholders(route, data)
        location.assign(route)
    }

    replacePlaceholders(str, data) {
        for ( const key in data ) {
            if ( !data.hasOwnProperty(key) ) {
                continue
            }

            str = String(str).replaceAll(':' + key, data[key])
        }

        return str
    }

    goBack() {
        history.back()
    }
}
