Source: kamlesh.js

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

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

	this.observables = [];

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

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

	// 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();
    };

    /**
     * Initial Markup
     * @private
     * @_template
     */
    _template() {
        wc.group("Kamlesh.template");
	
	var temp = `
	<div class="container-fluid alert alert-info">
	    <div class="row">
		<div class="col-6">
		    <h1 class="wc-font-m">
			Kamlesh

			<div id="my-btn-group" class="btn-group" role="group" aria-label="Basic example">
			    <button id="humana" type="button" class="btn btns btn-sm btn-primary">Humana</button>
			    <button id="ritter" type="button" class="btn btns btn-sm btn-primary">Ritter</button>
			    <button id="savoy" type="button" class="btn btns btn-sm btn-primary">Savoy</button>
			    <button id="savoy2" type="button" class="btn btns btn-sm btn-success">Savoy-II</button>
			</div>

		    </h1>
		</div>

		<div class="col-6 text-right">
		    <button class="btn btns btn-sm btn-success logout mt-2">Logout</button>
		</div>
	    </div>
	</div>

	<div class="container-fluid secret" style="display:none">
	    <div class="row">
		<div class="col-3"></div>

		<div class="col-6 mt-5 pt-5">
		    <input autocomplete="off" type="text" class="form-control wc-font-r p-5" id="my-text" placeholder="Say the magic word..." style="font-size:36px;font-weight:bold;">
		</div>

		<div class="col-3"></div>
	    </div>
	</div>

	<div id="csv-display"></div>
	`
	
	let self = this;

	wc.wait4(".btns", function() {
	    $(".btns").on("click", function() {
		tkloading.show();

		let id = $(this).attr("id")

		$(".btns").removeClass("active");
		$(this).addClass("active");

		$("#csv-display").empty();

		self._process(wc.toTitle(id));
	    });

	    $(".logout").on("click", function() {
		$.cookie("magic", false);
		document.location.reload();
	    });

	    if ($.cookie("magic") == "true") {
		$(".secret").hide()
		$("#table, .btns").show();
	    } else {
		$(".secret").show();
		$("#table").hide()

		wc.enterKey("#my-text", function() {
		    var kpaswd = kpaswd || "Kamlesh2020";
		    
		    let val = $("#my-text").val();
		    
		    if (val == kpaswd) {
			$(".secret").hide()
			$("#table, .btns").show();

			$.cookie("magic", true);
			$("table th:nth-child(1)").click();
		    } else {
			$("#my-text").val("");
		    }
		});	 
	    }

	    $("table th:nth-child(1)").click();
	}, 300);

        wc.groupEnd();
        return temp;
    };

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

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

	let obs = Kamlesh.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("Kamlesh._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("Kamlesh._fetchAttributes");
	
	this.properties = {
	    uparam	: "",
	    cname	: "Kamlesh",
	    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();
    };

    /**
     * Initialize component
     * @private
     * @_initialize
     */
    _initialize() {
	wc.group("Kamlesh._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("Kamlesh._finalize:", this.id);

	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.groupEnd();
    };

    /**
     * Invoked When component is removed. Usually with a .remove() function call
     * @disconnectedCallback
     */
    disconnectedCallback() {
        wc.group("Kamlesh.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("Kamlesh.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();
    };

    /**
     * _Process the instance object and artifacts
     * @_process
     */
    _process(id) {
	wc.group("Kamlesh._process");

	wc.csv2table("#csv-display",`/onedrive/Mel/Processed/${id}.csv`, "table table-striped table-condensed table-bordered")

	var table = $("#csv-display table").DataTable( {
            "footerCallback": function ( row, data, start, end, display ) {
		alert("FFFFFFFFFFFF");

		var api = this.api(), data;
		
		// Remove the formatting to get integer data for summation
		var intVal = function ( i ) {
                    return typeof i === 'string' ?
			i.replace(/[\$,]/g, '')*1 :
			typeof i === 'number' ?
                        i : 0;
		};
		
		// Total over all pages
		total = api
                    .column( 4 )
                    .data()
                    .reduce( function (a, b) {
			return intVal(a) + intVal(b);
                    }, 0 );
		
		// Total over this page
		pageTotal = api
                    .column( 4, { page: 'current'} )
                    .data()
                    .reduce( function (a, b) {
			return intVal(a) + intVal(b);
                    }, 0 );
		
		// Update footer
		$( api.column( 4 ).footer() ).html(
                    '$'+pageTotal +' ( $'+ total +' total)'
		);
            }
	});
	
	wc.wait4("#csv-display table", () => {
	    tkloading.show();

	    table.destroy();

	    //"scrollY": '75vh',

	    table = wc.table("#csv-display table", {
		"scrollX":      true,
		"order":	[],
		"bProcessing":	true,
		"bInfo":	false,
		"bFilter":	true,
		"paging":	false,
		"autoWidth": false
	    });

	    $("#csv-display table").attr("id",id);

	    setTimeout(() => {
		$("tfoot:first-child").css("background","#333").css("color","#FFF");

		$("tfoot:first-child td:nth-child(3)").html("TOTAL")

		$("#csv-display").on('order.dt search.dt', () => {
		    console.log(">>>>>>>>>>>>REDRAWN")
		});
	    }, 1000);

	    tkloading.hide();
	});
	
	wc.groupEnd();
    };
}

window.customElements.define('wc-kamlesh', Kamlesh);