Source: stock-trends.js

/**
 * Stock_trends Component<BR>
 * <BR><BR><img src=/tk/lib/components/w/img/stock-trends.png width=30% style="border:1px lime dashed;padding:20px">
 * <BR><BR><a href="/tk/lib/components/w/html/stock-trends.html">DEMO</a>
 */
class Stock_trends extends HTMLElement {
    constructor() {
        wc.group("Stock_trends.constructor")
	
        super();

	this.green = "#78e08f";
	this.red = "#eb2f06";
	this.gray = "#dfe4ea";

	this.values = [];

        wc.groupEnd();
    };
    
    /**
     * Set observable values here. When Changed, attributeChangedCallback is invoked
     * @observedAttributes
     */
    static get observedAttributes() {
        wc.group("Stock_trends.observedAttributes");

	this.observables = [];

        wc.groupEnd();
        return this.observables;
    };

    /**
     * Called when this is attached to DOM
     * @connectedCallback. 
     */
    connectedCallback() {
        wc.group("Stock_trends.connectedCallback")
	
	let self = this;

	// ADD A RANDOM ID IF NONE EXIST
	if (!this.id) {
	    this.id = this.constructor.name.toLowerCase() + "-" + wc.uid();
	}

	// GET PROPERTIES AND INTERESTING ELEMENTS
	this._initialize();

	// INITIALIZE VALUES
	for (var i = 0; i < this.properties.size; i++) {
	    this.values[i] = 0;
	}

	let html = "<div class=clearfix>";
	for (var i = 0; i < this.properties.size; i++) {
	    html += `<div id="wc-stock-trends-bar-${i}" class="wc-stock-trends-bar float-left" style="min-width:8px;margin-right:1px;background:${this.gray};">&nbsp;</div>`;
	}
	html += "</div>";

	// ADD COMPONENT MARKTOP
	this.innerHTML = html;

	// PUBLISH ALL EVENTS OF INTEREST
	this._publish();
	
	// SUBSCRIBE TO ALL EVENTS OF INTEREST
	this._subscribe();

	// ADD STATS AND OTHER FINAL STUFF
	this._finalize();

	ga('send', {'hitType': 'event','eventCategory': 'wc-stock-trends-connected','eventAction': 'connected','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});

        wc.groupEnd();
    };

    /**
     * Initial Markup
     * @private
     * @_template
     */
    _template() {
        wc.group("Stock_trends.template");
	
	var temp = this.dom.content;

        wc.groupEnd();
        return temp;
    };

    /**
     * Called with .setAttribute(...) function call
     * @attributeChangedCallback
     */
    attributeChangedCallback(attr, oldval, newval) {
        wc.group("Stock_trends.attributeChangedCallback:", attr, oldval, newval);

	this.properties = this.properties || [];

	let obs = Stock_trends.observedAttributes;

	for (let i = 0; i < obs.length; i++) {
	    if (newval) {
		this.properties[obs[i]] = newval;
	    }
	}
	
	// YOUR CODE FOR CHANGES GO HERE (MAYBE NULL FIRST TIME THROUGH)
	try {
	    switch(attr) 
	    {
		case "header":
		//this.querySelector("h1").innerHTML = newval;
		break;
		
		default:
		break;
	    }
	} catch(e) {
	    wc.warn(e.name + ' > ' + e.message);
	}

        wc.groupEnd();
    };

    /**
     * Stores DOM elements of interest for future use
     * @private
     * @_fetchElements
     */
    _fetchElements() {
	wc.group("Stock_trends._fetchElements");
	
	this.dom = this.dom || [];
	this.dom.content = this.innerHTML;

	wc.groupEnd();
    };

    /**
     * Component attributes are _fetched and defaults are set if undefined
     * @private
     * @_fetchAttributes
     */
    _fetchAttributes() {
	wc.group("Stock_trends._fetchAttributes");
	
	this.properties = {
	    uparam	: "",
	    cname	: "Stock_trends",
	    author	: "Mel M. Heravi, Ph.D.",
	    version	: "1.0"
	};
	
	// SAVE WIDGET SPECIFIC PROPERTIES
	this.propertiesW = [];
	
	// SAVE ALL OTHER PROPERTIES
	let attrs = wc.getAttributes(this)
	
 	for (var key in attrs) {
	    let attr = this.getAttribute(key) || this.properties.key;
	    this.properties[key]  = this.getAttribute(key);
	    this.propertiesW[key] = this.getAttribute(key);
	    wc.log(key + ": " + attrs[key]);
	}

	// SET ALL INITIAL ATTRIBUTES
 	for (var key in this.properties) {
	    switch(key) 
	    {
		case "header":
		break;
		
		default:
		break;
	    }
	}

	wc.log("ATTRIBUTES: ", this.properties);

	wc.groupEnd();
    };

    /**
     * configure the instance object and artifacts
     * @configure
     * @param {string} data use data if exist else use 'this.properties.cfg' parameter
     */
    configure(data) {
	wc.group("Stock_trends.configure:", data);

	// IF JSON VARIABLE (data) IS PROVIDED
	if (data) {
	    this._process(data);
	} else {
	    let self = this;

	    $.getJSON(this.properties.cfg, function(data) {
		self._process(data);
	    }).fail(function(jqXHR, textStatus, errorThrown) {
		alert("ERROR: INCOMING TEXT " + jqXHR.responseText);
	    });
	}

	wc.groupEnd();
    };

    /**
     * _process the instance object and artifacts
     * @private
     * @_process
     */
    _process(data) {
	wc.group("Stock_trends._process:", data);
	
	// DO WHATEVER WITH THE DATA
	
	wc.groupEnd();
    };

    /**
     * Initialize component
     * @private
     * @_initialize
     */
    _initialize() {
	wc.group("Stock_trends._initialize:", this.id);

	// FETCH ALL INTERESTING ELEMENTS
	this._fetchElements();

	// FETCH ALL ATTRIBUTES
	this._fetchAttributes();
	
	wc.groupEnd();
    };

    /**
     * Save data for analytics and final wrap up
     * @private
     * @_finalize
     */
    _finalize() {
	wc.group("Stock_trends._finalize:", this.id);

	let self = this;

	this.classList.add("wc");

	// ADD ANALYTICS HERE
	wc.setStats(this, this.properties.cname, this.properties.version);
	
	// SHOW IT NOW (NO FLICKERS) 
	this.style.visibility = "visible";

	wc.publish("wc-stock-trends-ready", {
	    time: new Date().getTime(),
	    action: "click",
	    id: self.id
	});

	wc.groupEnd();
    };

    /**
     * Invoked When component is removed. Usually with a .remove() function call
     * @disconnectedCallback
     */
    disconnectedCallback() {
        wc.group("Stock_trends.disconnectedCallback")

	ga('send', {'hitType': 'event','eventCategory': 'wc-stock-trends-disconnected','eventAction': 'disconnected','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});

        wc.groupEnd();
    };

    /**
     * Publish all to events of interest
     * @private
     * @_publish
     */
    _publish() {
	wc.group("Stock_trends._publish:", this.id);

	let self = this;

	// PUBLISH STUFF HERE

	wc.groupEnd();
	return true;
    };

    /**
     * Subscribe all to events of interest
     * @private
     * @_subscribe
     */
    _subscribe() {
	wc.group("Stock_trends._subscribe:", this.id);
	
	let self = this;

	// SUBSCRIBE TO REQUESTS FROM CLIENTS
	wc.subscribe("wc-stock-trends", function(msg,data) {
	    wc.info(`SUBSCRIPTION TRIGGERED ${JSON.stringify(data)}`)

	    // ADD IT TO CORRECT TRENDS
	    if (self.id == data.id) {
		$("#" + data.id)[0]._add(data);
	    }

	    ga('add', {'hitType': 'event', 'eventCategory':'wc-stock-trends', 'eventAction':'add', 'eventLabel':self.properties.cname, 'eventValue':JSON.stringify({'env':wcENV, 'app':wcAPP, 'url':wcURL})});
	});

	wc.groupEnd();
    }

    /**
     * Destroy the instance object and artifacts
     * @destroy
     */
    destroy() {
	wc.group("Stock_trends.destroy");

	// FREE ALL MEMORY
	// you should delete all created objects here
	
	// FREE POINTER
	delete this;
	
	// REMOVE ITEM FROM DOM
	this.parentNode.removeChild(this);

	ga('send', {'hitType': 'event','eventCategory': 'wc-stock-trends-destroyed','eventAction': 'distroy','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});

	wc.groupEnd();
    };

    /**
     * Add the instance object and artifacts
     * @_add
     */
    _add(data) {
	wc.group("Stock_trends._add:", JSON.stringify(data));

	this.values.shift()
	this.values.push(data.value);

	for (var i = 0; i < this.properties.size; i++) {
	    if (i == 0 && this.values[i] != 0) {
		if (this.values[i] > this.values[i+1]) {
		    $(`#${this.id} #wc-stock-trends-bar-${i}`).css("background", this.green)
		} else if (this.values[i] < this.values[i+1]) {
		    $(`#${this.id} #wc-stock-trends-bar-${i}`).css("background", this.red)
		} else if (this.values[i] == this.values[i+1]) {
		    $(`#${this.id} #wc-stock-trends-bar-${i}`).css("background", $(`#${this.id} #wc-stock-trends-bar-${i-1}`).css("background"))
		}
	    } else {
		if (this.values[i] > this.values[i-1]) {
		    $(`#${this.id} #wc-stock-trends-bar-${i}`).css("background", this.green)
		} else if (this.values[i] < this.values[i-1]) {
		    $(`#${this.id} #wc-stock-trends-bar-${i}`).css("background", this.red)
		} else if (this.values[i] == this.values[i-1]) {
		    $(`#${this.id} #wc-stock-trends-bar-${i}`).css("background", $(`#${this.id} #wc-stock-trends-bar-${i-1}`).css("background"))
		}
	    }
	}

	//wc.log(this.values.length, this.values);

	//ga('send', {'hitType': 'event','eventCategory': 'wc-stock-trends-add','eventAction': 'distroy','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});

	wc.groupEnd();
    };

    /**
     * @test
     */
    static test() {
	wc.group("Stock_trends.test");

	for (var i = 0; i <= 100; i++) {
	    setTimeout(function(){
		wc.publish("wc-stock-trends", {
		    time: new Date().getTime(),
		    action: "add",
		    id: "my-stock-trends-1",
		    value: Math.floor(Math.random() * 10)
		});
	    }, i*1000);
	}
	
	for (var i = 0; i <= 100; i++) {
	    setTimeout(function(){
		wc.publish("wc-stock-trends", {
		    time: new Date().getTime(),
		    action: "add",
		    id: "my-stock-trends-2",
		    value: Math.floor(Math.random() * 10)
		});
	    }, i*1000);
	}

	wc.groupEnd();
	return true;
    }
}

window.customElements.define('wc-stock-trends', Stock_trends);

// SO I CAN CALL THE STATIC METHOD GLOBALLY
window.Stock_trends = Stock_trends;