/**
 * Setup the ida/gewoba bot.
 */
$iso(document).ready(function () {
    let thisScript = $iso("script[src$='ida/gewoba/js']");

    let debug = false;
    let debugAttr = thisScript.attr('data-debug');
    if (typeof debugAttr !== typeof undefined && debugAttr !== false) debug = true;

    const data = {'username': 'bot', 'username_long': 'Chatbot', 'username_initials': 'BOT', 'team': 'ida', 'bot': 'gewoba', 'label': 'Digitale Assistenz', 'welcome_msg': 'Hallo, ich bin die digitale Assistenz der GEWOBA. Stellen Sie mir einfach Ihre Fragen. Am besten verstehe ich einfache Sätze, freue mich aber über alle Anfragen. Sie helfen mir, mich stetig zu verbessern.', 'info_msg': 'Um mich zu aktivieren, schicken Sie mir eine Nachricht oder klicken Sie für Beispielanfragen unten auf das Fragezeichen.', 'privacy': 'https://www.gewoba.de/datenschutz'};

    if(data.key)
        addBotKey(data.team, data.bot, data.key);
    if(data.privacy)
        setBotPrivacyLink(data.team, data.bot, data.privacy);

    $iso('#idabot a.ida-bot-link[data-ida-team=' + data.team + '][data-ida-bot=' + data.bot + ']').each(function () {
        let $this = $iso(this);

        // add bot data and display
        $this.data('botdata', data);
        $this.css('display', 'block');

        let popoverMessage = '🤖 Chatbot einblenden'
        let popoverMessageAttr = $this.attr('data-ida-popover');
        if (typeof popoverMessageAttr !== typeof undefined) popoverMessage = popoverMessageAttr;

        // setup popover
        $this.bsiso_popover({
            'content': function () {
                // get current icon
                let currentIcon = $this.data('icon');
                // activate is default in the beginning
                if(!currentIcon)
                    currentIcon = 'activate';

                return (currentIcon === 'activate' ? popoverMessage : 'Beenden und schließen 👋');
            },
            'container': '#idabot a.ida-bot-link[data-ida-team=' + data.team + '][data-ida-bot=' + data.bot + ']',
            'placement': 'left',
            'trigger': 'hover'
        });

        // room joining and leaving via chat (bubble) button
        $this.click(function () {
            let link = $this;
            let teamname = link.attr('data-ida-team');
            let botname = link.attr('data-ida-bot');

            // search for existing bot chat card (could be a fake card too)
            let existingBox = $iso('#idawebchat').find('.chat-box[data-ida-team="' + teamname + '"][data-ida-bot="' + botname + '"]');

            // find out if we are in a room for this bot (meaning the bot has been activated)
            let roomid = null;

            $iso.each(rooms, function(key, value) {
                let [value_teamname, value_botname] = value
                if (value_teamname === teamname && value_botname === botname)
                    roomid = key;
            });

            if (!roomid && !existingBox.length) { // we have neither a room nor a card so show intro
                introduceBot.call(this, 400, 800)
                updateBotLink(link);
            } else if (roomid && existingBox.length) { // we have a room a well as a card so...
                if (existingBox.is(":visible")) { // ...leave chat if the card is visible
                    existingBox.find('.close-modal').bsiso_modal('show');
                } else { // ...unminimize card if it is not visible
                    const card = existingBox.find('.chat-card');
                    unminimizeCard(card, function () {
                        updateBotLink(link);

                        // focus on message field
                        card.find('input.message').focus();
                    });

                    if (playSounds) sizeSound.play();
                }
            } else if (!roomid && existingBox.length) { // we are not in room but have a card so...
                if (existingBox.closest('.chat-box').is(":visible")) { // ...close card if visible
                    const card = existingBox.find('.chat-card');
                    closeCard(card, function () {
                        updateBotLink(link);
                        updateWebchatDisplay();
                    });
                } else { // ...unminimize card if it is not visible
                    const card = existingBox.find('.chat-card');
                    unminimizeCard(card, function () {
                        updateBotLink(link);

                        // focus on message field
                        card.find('input.message').focus();
                    });
                }
            } else { // we are in the room but do not have a card so something is terrible wrong in we better leave the room
                socket.send(JSON.stringify({
                    "command": "leave",
                    "room": data.lazyjoin,
                }));
            }

            return false;
        });

        // set animation durations
        let durationLong = 800;
        let durationShort = 400
        if (debug) {
            durationLong = 80;
            durationShort = 40;
        }
        let introDelay = durationLong;

        // fly in bot links
        if($this.hasClass('ida-fly-in')) {
            introDelay += durationLong;
            setTimeout(() => {
                $this.removeClass('ida-fly-in');
                let targetTop = $this.position().top
                $this.addClass('ida-fly-in');

                $this.animate({
                    top: targetTop,
                }, durationLong, function () {
                    $this.css({'top': ''});
                    $this.removeClass('ida-fly-in');
                });
            }, durationLong);
        }

        // show popover
        if(!$this.hasClass('ida-intro')) {
            setTimeout(() => {
                $this.bsiso_popover('show');
            }, introDelay + durationLong);
        }

        // intro bot links
        if($this.hasClass('ida-intro')) {
            setTimeout(() => {
                introduceBot.call($this, durationShort, durationLong);
                updateBotLink($this);
            }, introDelay);
        }
    });
});
