Source: stock-chart.js

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

	this.hc    = null;
	this.step  = 0;
	this.color = {cred: "#ef9a9a", cgreen: "#81C784", bred: "#ffebee", bgreen: "#F1F8E9"}

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

	this.observables = [];

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

    /**
     * Called when this is attached to DOM
     * @connectedCallback. 
     */
    connectedCallback() {
        wc.group("Stock_chart.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();

	// ADD COMPONENT MARKTOP
	this.innerHTML = this._template()

	this._setup();

	// 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-connected','eventAction': 'connected','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});

        wc.groupEnd();
    };

    /**
     * @_template
     */
    _template() {
        wc.group("Stock_chart.template");
	
	var temp = ``;

        wc.groupEnd();
        return temp;
    };

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

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

	let obs = Stock_chart.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
     * @_fetchElements
     */
    _fetchElements() {
	wc.group("Stock_chart._fetchElements");
	
	this.dom = this.dom || [];
	this.dom.content = this.innerHTML;

	wc.groupEnd();
    };

    /**
     * Component attributes are _fetched and defaults are set if undefined
     * @_fetchAttributes
     */
    _fetchAttributes() {
	wc.group("Stock_chart._fetchAttributes");
	
	this.properties = {
	    uparam	: "",
	    cname	: "Stock_chart",
	    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_chart.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
     * @_process
     */
    _process(data) {
	wc.group("Stock_chart._process:", data);
	
	// DO WHATEVER WITH THE DATA
	
	wc.groupEnd();
    };

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

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

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

    /**
     * Save data for analytics and final wrap up
     * @_finalize
     */
    _finalize() {
	wc.group("Stock_chart._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-chart-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_chart.disconnectedCallback")

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

        wc.groupEnd();
    };

    /**
     * Destroy the instance object and artifacts
     * @destroy
     */
    destroy() {
	wc.group("Stock_chart.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-destroyed','eventAction': 'distroy','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});

	wc.groupEnd();
    };

    /**
     * @_publish
     */
    _publish() {
	wc.group("Stock_chart._publish");

	let self = this;
	
	wc.groupEnd();
	return true;
    };

    /**
     * Subscribe all to events of interest
     * @_subscribe
     */
    _subscribe() {
	wc.group("Stock_chart.subscribe:", this.id);
	
	let self = this;
	
	// SUBSCRIBE TO REQUESTS FROM CLIENTS
	wc.subscribe("wc-stock-chart", function(msg,data) {
	    wc.info(`SUBSCRIPTION TRIGGERED ${JSON.stringify(data)}`)

	    let w = $("#" + data.id)[0];

	    // ADD TO CORRECT CHART
	    w._add(0, [++w.step, data.value])

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

	wc.groupEnd();
    }

    /**
     * @_setup
     */
    /////////////////////////////////////////////////////////////////////////
    //// 
    /////////////////////////////////////////////////////////////////////////////
    _setup() {
	wc.group("Stock_chart._setup");

	let self = this;

	window.xx = this.hc = Highcharts.chart(this.id, {
	    chart: {
		type: 'spline',
		animation: Highcharts.svg, // don't animate in old IE
		backgroundColor: '#FFF',
		marginRight: 5,
		marginLeft: 5,
	    },

	    plotOptions:{
		series:{
		    lineColor: "#666",
                    lineWidth: 1
		}
            },
        
	    credits: {
		enabled: false
	    },

	    title: {
		style: {
		    fontSize: '12px',
		    color: "#4a69bd"
		},
		text: this.properties.symbol,
		align: 'left',
	    },

	    xAxis: {
		type: 'linear',
		labels: {
		    align: "left",
		    format: '{value:.2f}',
		    x: 0,
		    style: {
			fontSize: '9px',
			color: '#000'
		    }
		}
	    },

	    yAxis : [{
		title: {
		    text: null,
		    style: {
			color: Highcharts.getOptions().colors[2]
		    }
		},
		labels: {
		    align: "left",
		    format: '{value:.2f}',
		    x: 0,
		},

		opposite: false,

		labels: {
		    align: "left",
		    format: '{value:.2f}',
		    x: 0,
		    style: {
			fontSize: '9px',
			color: '#000'
		    }
		}
	    }, {
		title: {
		    text: null,
		    style: {
			color: Highcharts.getOptions().colors[0]
		    }
		},
		labels: {
		    align: "right",
		    format: '{value}',
		    x: 0,
		    style: {
			fontSize: '9px',
			color: '#000'
		    }
		}
	    }],

	    legend: {
		enabled: false
	    },

	    exporting: {
		enabled: false
	    },

	    series: [{
		showInLegend: false,
		name: this.properties.symbol,
		yAxis: 0,
		color: "#000",
		marker: {
		    enabled: false,
		    radius: 3
		},
		data: []
	    }]
	});

	setTimeout(() => {
	    // CHANGE CHART HEIGHT
	    this.hc.setSize($("document").width(),this.properties.height)
	}, 200);

	wc.groupEnd();
    }

    /**
     * @_add
     */
    _add(series, arg) {
	console.group("Stock_chart._add:", series, arg);

	let price  = arg[1];

	if (typeof websocket != "undefined") {
	    var change = websocket.change[this.properties.symbol];
	}

	if (typeof change === "undefined") {
	    var change = "";
	    var ccolor = "#CCC";
	    var bcolor = "#CCC";
	} else {
	    if (change < 0) {
		var change = ` | <font color="${this.color.cred}">${change.toFixed(3)}</font>`;
		var ccolor = this.color.cred;
		var bcolor = this.color.bred;
	    } else if (change > 0) {
		var change = ` | <font color="${this.color.cgreen}">${change.toFixed(3)}</font>`;
		var ccolor = this.color.cgreen;
		var bcolor = this.color.bgreen;
	    }
	}
	
	$(`.wc-green-q-price`).html(" $" + wc.commify(price.toFixed(2)) + change);
	
	$(`.wc-green-q-price`)
	    .parent().parent().parent()
	    .css("background",bcolor)

	// REMOVE ONE IF REACHED MAX 2 MINUTS
	this._prune();

	this.hc.series[0].addPoint(arg)

	console.groupEnd();
    };

    /**
     * @_prune
     */
    _prune() {
	console.group("chart.prune");

	this.secs = this.properties.seconds || 60;
	console.log(">>>>>>>>>>", this.secs);

	if (this.hc.series[0].data.length > this.secs) {
	    this.hc.series[0].data[0].remove();
	}

	console.groupEnd();
    };

    /**
     * @test
     */
    static test() {
	wc.group("Stock_chart.test");
	
	let ticks = 35;

	for (var i = 0; i < ticks; i++) {
	    setTimeout(() => {
		wc.publish("wc-stock-chart", {
		    time: new Date().getTime(),
		    action: "add",
		    id: "my-stock-chart-1",
		    value: Math.floor(Math.random() * 5000)
		});

		wc.publish("wc-stock-trends", {
		    time: new Date().getTime(),
		    action: "add",
		    id: "my-stock-trends-melify",
		    value: Math.floor(Math.random() * 100)
		});
	    }, i*500);
	}

	for (var i = 0; i < ticks; i++) {
	    setTimeout(() => {
		wc.publish("wc-stock-chart", {
		    time: new Date().getTime(),
		    action: "add",
		    id: "my-stock-chart-2",
		    value: Math.floor(Math.random() * 5000)
		});

		wc.publish("wc-stock-trends", {
		    time: new Date().getTime(),
		    action: "add",
		    id: "my-stock-trends-msft",
		    value: Math.floor(Math.random() * 100)
		});
	    }, i*500);
	}

	wc.groupEnd();
	return true;
    }
}

window.customElements.define('wc-stock-chart', Stock_chart);

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