import { NativeModules } from 'react-native'

import { createInteractor } from '../architecture/Interactor'
import { check } from '../utility/check'
import { log } from '../utility/log'

export const createDependency = () => {}

type WebInterfaceInteractor = {
    createWebInterfaceScript(webToken: string, postMessageScript: string): Promise<string>
    handleWebInterfaceCommand(command: string): void
}

createDependency.WebInterfaceModule = () => ({
    interactor: createInteractor<WebInterfaceInteractor>(NativeModules.WebInterfaceInteractor),
})

export type WebInterfaceModule = ReturnType<typeof createWebInterfaceModule>

export const createWebInterfaceModule= () => {
    // create dependency
    const { interactor } = createDependency.WebInterfaceModule()

    // define method
    const createWebInterfaceScript = async (
        webToken: string,
        postMessageScript: string,
    ) => {
        if (!check.string(webToken)) {
            log.unmatchedType('webToken', 'string')
            return undefined
        }
        if (!check.string(postMessageScript)) {
            log.unmatchedType('postMessageScript', 'string')
            return undefined
        }

        return await interactor.createWebInterfaceScript(webToken, postMessageScript)
    }
    
    const handleWebInterfaceCommand = (command: string) => {
        if (!check.string(command)) {
            log.unmatchedType('command', 'string')
            return undefined
        }

        interactor.handleWebInterfaceCommand(command)
    }

    // create object
    return {
        createWebInterfaceScript,
        handleWebInterfaceCommand,
    }
}
