//# sourceURL=widgets/Sensor.js
/**
 * $Id: Sensor.js 300 2018-03-08 18:56:13Z patrick $
 */

import Widget from '../Widget.js';

var Sensor = function( elem ) {
    Widget.call( this, elem );
    this.name = "Sensor";
    this.entity_id = this.getData( 'sensor', this.entity_id );

    this.value = this.getData( 'value', 'entity.primary_value' );
    this.active_id = this.getData( 'active', false );
    this.active_entity = false;

    $(this.elem).addClass("widget-sensor");
};

Sensor.prototype = Object.create(Widget.prototype);
Sensor.prototype.constructor = Sensor;

Sensor.prototype.startXXX = function() {
    /* If our active state is tracked by a reference/expression, find that
       entity and make us an observer of it. */
    const self = this;
    if ( self.active_id ) {
        self.addObservedEntity( self.active_id, "active_entity" ).catch( function( e ) {
            self.log.warn("Unable to load active entity %1: %2", self.active_id, e);
        });
    }
};

Sensor.prototype.updateXXX = function() {
    let active = this.entity ? this.entity.getAttributeBoolean("state") : false;
    if ( this.active_entity ) {
        const val = this.resolve( this.active_id, this.createContextFromEntity( this.active_entity ) );
        active = this.active_entity.toBooleanState( val, false );
    }

    this.bindValues( this.createContextFromEntity( this.entity ) );

    if ( active ) {
        $(this.elem).addClass("active").removeClass('update-pending');
    } else {
        $(this.elem).removeClass("active update-pending");
    }
};

Sensor.prototype.post_update = async function() {
    const $target = $( '.widget-value', $(this.elem) );
    // console.log( 'Sensor.post_update() on', this, 'to', $target );
    if ( ! $target.hasClass( 'text-size-elastic' ) ) {
        return;
    }
    const $body = $( '.widget-body', $(this.elem) );
    const vpad = $body.height() - 2 * ( $( '.widget-title', $(this.elem) ).height() + 16 );
    const vwid = $body.width();
    console.log(this,vwid,vpad);
    $target.css( 'font-size', '' );
    let size = parseInt( $target.css( 'font-size' ), 10 );
    while ( size > 8 && ( $target.width() > vwid || $target.height() > vpad ) ) {
        $target.css( 'font-size', --size );
        console.log('size now',size,'width',$target.width(),'height',$target.height() );
    }
}

export default Sensor;
