import { IntegrationAPI } from "../../IntegrationApi";
const { Atem } = require('atem-connection')

module.exports = (Api: IntegrationAPI) => {
    //----- ATEM -----
    Api.registerAction('atem_setPreview', 'Set Atem preview', require('./actions/atem/setPreview'))
    Api.registerAction('atem_setProgram', 'Set Atem program', require('./actions/atem/setProgram'))
    Api.registerAction('atem_fadeToBlack', 'Atem fade to black', require('./actions/atem/fadeToBlack'))

    Api.registerConnectionValidator('bm_atem', (validatorAPI) => {
        var ip = validatorAPI.properties.ip;

        var timeout: NodeJS.Timeout;
        var res = (valid: boolean, message?: string) => {
            res = () => { };
            validatorAPI.callback(valid, message)
            clearTimeout(timeout)
        }

        timeout = setTimeout(() => {
            res(false, 'Timeout whilst trying to connect to atem')
        }, 5000);

        var atem = new Atem({ debugBuffers: true })

        atem.on('error', (error) => {
            res(false, error)
        })

        atem.on('connected', () => {
            validatorAPI.setInstance(atem)

            res(true)
        })

        atem.connect(ip)
    })
}