import { ActionAPI } from "../../../../ActionAPI"
import { EditorAPI } from "../../../../EditorAPI"
const { Atem } = require('atem-connection')

module.exports = (ActionAPI: ActionAPI) => {
    ActionAPI.onExecute((properties, status) => {
        var connectionID = properties.connectionID != undefined ? properties.connectionID : "none"

        if (connectionID != 'none') {
            var connection = ActionAPI.getConnection('bm_atem', connectionID)
            if (connection && connection.instance) {
                var atem = connection.instance;

                atem.fadeToBlack().then(() => {
                    status(`Atem fade to black`, 'info')
                }).catch((error) => {
                    status(`Error whilst setting atem fadetoblack: ${error}`, 'error')
                })
            } else status('Atem is not online', 'error')
        } else status('No connection specified', 'error')
    })

    ActionAPI.onOpenEditor((EditorAPI: EditorAPI, properties: any) => {
        var connectionID = properties.connectionID != undefined ? properties.connectionID : "none"

        EditorAPI.onFieldChanges((fields) => {
            var fieldObject = EditorAPI.tools.objectifyFieldsValues(fields)

            connectionID = fieldObject.connectionID

            EditorAPI.saveProperties({ connectionID })
        })

        EditorAPI.setFields([{
            id: 'connectionID',
            name: "Connection",
            type: "connection",
            connectionType: "bm_atem",
            value: connectionID
        }])
    })
}