/** This file is part of Reactor.
 *  Copyright (c) 2020-2025 Kedron Holdings LLC, All Rights Reserved.
 *  Reactor is not public domain or open source. Distribution or derivative works are expressly prohibited.
 */

export const version = 25141;

import api from '/client/ClientAPI.js';
import { mixin } from '/client/util.js';

import Observer from '/client/Observer.js';

import { idSelector } from './reactor-ui-common.js';

export default class Tab {
    constructor( id, $container ) {
        this.id = id;
        this.$parent = $container;

        if ( $( `div#${idSelector(id)}` ).length ) {
            console.error( "Tab",id,"already exists" );
            $( `div#${idSelector(id)}` ).remove();
        }
        this.$tab = $( '<div></div>' )
            .attr( 'id', this.id )
            .data( 'tabobject', this )
            .addClass( 're-tab-container' )
            .appendTo( this.$parent )
            .hide();

        this.$tab.on( 'activate', this.activate.bind( this ) );
        this.$tab.on( 'suspend', this.suspend.bind( this ) );

        /* Our styles. */
        if ( 0 === $( 'link#' + idSelector( this.id + '-styles' ) ).length ) {
            let tag = this.id.replace( /^tab-/, "" );
            $('head').append( '<link id="' + this.id + '-styles" href="lib/css/reactor-ui-' + tag + '.css" rel="stylesheet">' );
        }
    }

    /* Observer */
    toString() {
        return this.constructor.name;
    }

    getTabElement() {
        return this.$tab;
    }

    async activate( /* event, extras */ ) {
    }

    suspend( event ) {  // eslint-disable-line no-unused-vars
        // console.log( `Tab ${this.id} super.suspend() running` );
        // console.log(event);

        /*
        var $tab = $( event.target );
        if ( this.id !== $tab.attr( 'id' ) || !$tab.hasClass( "re-tab-container" ) ) {
            console.log( "    event is not for the tab, but a child" );
            return;
        }
        */

        if ( ! this.canSuspend() ) {
            return false;
        }

        this.suspending();

        this.active = false;

        this.unsubscribe();
        api.off( '.' + this.id );

        this.$tab.empty();

        try {
            const d = { ...this.$tab.data() };  // .data() returns interval, live structure, so must CLONE!
            delete d.tabobject;  // remove ours
            if ( Object.keys( d ).length > 0 ) {
                console.warn( "Suspending tab", this, "uncleared post-suspend DOM data is", d );
            }
            this.dump_observed();
        } catch ( err ) {
            console.log( err );
        }

        return true;
    }

    canSuspend() {
        return true;    /* default implementation */
    }

    /** Called when a suspend is in progress */
    suspending() {
        /* Default implementation does nothing. */
    }
}

mixin( Tab, Observer );
