/*
 ============================================================================
   Web Solution Project, ID SW Development Department, LG ELECTRONICS INC., SEOUL, KOREA
   Copyright(c) 2021 by LG Electronics Inc.
   IDCAP extension version : 1.1.0
 ============================================================================
*/
var extIDCAPSecure,extRegisterIDCAPCloseHandler,extDisableIdcapConsoleLog,extWebWorker,isSubscribeParam,retry_count,idcap;
if(void 0===idcap)if("object"===typeof window)(function(){function b(a){1==idcap.isLogEnabled&&(a=1024<a.length?a.substring(0,1024):a,!0!==extWebWorker&&console.log(a))}function n(a,e){if(!0!==extWebWorker){var g="",l=document.createEvent("HTMLEvents");b(p("event received, ",e));l.initEvent(a,!0,!1);for(g in e)e.hasOwnProperty(g)&&(l[g]=e[g]);document.dispatchEvent(l)}}idcap={API_VERSION:"1.1.0",isRemoteInitialize:!1,isRemote:!1,remote_ip:"",isLogEnabled:!1,isMaxCount:4};var h=0,c=[{command_id:"0",
param_text:'{"command_id" : "0", "command" : "notify_sdk_version","parameters":{"idcap_js_extension_version" : "1.1.0"}}'}],k=[{command:"0",param_text:'{"command" : "0", "command" : "notify_sdk_version", "parameters":{"idcap_js_extension_version" : "1.1.0"}}'}],d=null,q=!1,v=!1,r=!1,A=null,w=null,E=null,B=!1,p=null,C=!1,z=!1,D=0,x="127.0.0.1";!0!==idcap.isLogEnabled?!0!==extWebWorker&&console.log("ID -  console log is disabled"):!0!==extWebWorker&&console.log("ID -  console log is enabled");b("check external value : extDisableIdcapConsoleLog = "+
extDisableIdcapConsoleLog+", extIDCAPSecure = "+extIDCAPSecure+", extRegisterIDCAPCloseHandler = "+extRegisterIDCAPCloseHandler);B=function(){var a=navigator.userAgent;a.match(/Windows/);a.match(/Macintosh/);a.match(/Mac OS X/);var e=a.match(/Web0S/),g=a.match(/SmartTV/),l=a.match(/WebAppManager/);b("UA = '"+a+"'");return e||g||l?(z=!1,idcap.isRemote=!1):z=idcap.isRemote=!0}();p=function(a,e){var g="";var l=[],t="";for(g in e)e.hasOwnProperty(g)&&l.push(g);l.sort();for(g=0;g<l.length;g+=1){var u=
g,f=l,m="",y="";var F=f[u];try{m=e[F],y=typeof m}catch(G){m="<unknown value>",y="unknown"}"function"===y?m="{/*function*/}":"object"===y?m=p("",m):"string"===y&&(m='"'+m+'"');t+='"'+F+'" : '+m;u<f.length-1&&(t+=", ")}return a+"{"+t+"}"};A=function(){b("initialize_idcap_websocket");v?b("websocket : connection is in progress"):(v=!0,0==z?!0!==extIDCAPSecure?(b("default idcap connection"),d=new WebSocket("ws://127.0.0.1:8153/hcap_command")):(b("secure idcap connection"),d=new WebSocket("wss://localhost:8154/idcap_command")):
(b("remote connection"),d="https:"===location.protocol?new WebSocket("wss://"+x+":8154/idcap_command"):new WebSocket("ws://"+x+":8153/idcap_command")),d.onopen=function(){b("websocket : onopen");v=!1;q=!0;setTimeout(w,5)},d.onmessage=function(a){a=JSON.parse(a.data);var e=a.command_id,g=a.command,l=a.result;b("ws.onmessage : "+JSON.stringify(a));if("event"===e)"debug_event_received"===g?(a.enable_log?!0!==extWebWorker&&console.log("idcap console log is enabled"):!0!==extWebWorker&&console.log("idcap console log is disabled"),
extDisableIdcapConsoleLog=!a.enable_log):n(g,a);else{if(0<c.length&&c[0].command_id===e){b(p("command_id = "+e+" received, ",a));if(l)if(c[0].onSuccess)try{c[0].onSuccess(a)}catch(f){b(p("exception : onSuccess : "+f))}else c[0].resolve&&c[0].resolve(a);else if(c[0].onFailure)try{c[0].onFailure(a)}catch(f){b(p("exception : onFailure : "+f))}else c[0].reject&&c[0].reject(a);c.splice(0,1)}else{var t=0,u=!1;k.forEach(function(f){null!==f&&void 0!==f.command&&f.command===g&&(t=k.indexOf(f),u=!0)});if(u){if(k[t].onSuccess)try{k[t].onSuccess(a)}catch(f){b(p("exception : onSuccess : "+
f))}}else b(p("invalid response from server ",a))}r=!1;w()}},d.onclose=function(){b("websocket : onclose");r=q=v=!1;D+=1;b("retry-count",D);!z&&D<idcap.isMaxCount?setTimeout(w,50):b("Max retry - stop websocket connection try")},"onbeforeunload"===extRegisterIDCAPCloseHandler?window.onbeforeunload=function(){b("close idcap websocket in onbeforeunload handler");d.onclose=function(){};d.close()}:"onunload"===extRegisterIDCAPCloseHandler&&(window.onunload=function(){b("close idcap websocket in onunload handler");
d.onclose=function(){};d.close()}))};w=function(){b("start_cmd_loop");if(!r){r=!0;if(q){if(0<c.length){b("webSocket sending");b(p("command_id = "+c[0].command_id+" sent, ",JSON.parse(c[0].param_text)));d.send(c[0].param_text);return}}else A();r=!1}};E=function(a,e={}){if(null===a||""===a||void 0===a)b("[ERROR] Command should not be null.");else if(!1===a.toLowerCase().startsWith("idcap://"))b("[ERROR] wrong IDCAP command.");else if(Array.isArray(e))b("[ERROR] Command Parameter Error. param is Array type or not defined.");
else{B&&b("[ERROR] IDCAP is unavailable on this browser.");h=1024<h?0:h+1;var g=h.toString(),l="";e.command_id=g;e.command=a;l=JSON.stringify(e,null);b("param_text : "+l);for(name in e)"subscribe"===name&&e.hasOwnProperty("subscribe")&&!0===e.subscribe&&(C=!0);if(C)k.forEach(function(f){null!==f&&void 0!==f.command&&f.command===e.command?b("already registered. : "+a):k[k.length]={command:a,param_text:l,onSuccess:e.onSuccess,onFailure:e.onFailure}}),C=!1;else{var t=0,u=!1;k.forEach(function(f){null!==
f&&void 0!==f.command&&f.command===e.command&&(t=k.indexOf(f),u=!0)});u=u?k.splice(t,1):!1}return new Promise((f,m)=>{c.push({command_id:g,param_text:l,resolve:f.bind(this),reject:m.bind(this),onSuccess:e.onSuccess,onFailure:e.onFailure});b(p("command_id = "+g+" added, ",c[c.length-1]));w()})}};B||setTimeout(w,200);idcap.remoteInitialize=function(a){b("remoteInitialize");x=a;b("remote = "+x);idcap.remote_ip=x;A();idcap.isRemoteInitialize=!0};idcap.remoteFinalize=function(){b("remoteFinalize");d.close();
d=null;idcap.remote_ip="";idcap.isRemoteInitialize=!1};idcap.request={};idcap.request=function(a,e){a=a.toLowerCase();return E(a,e)}})();else{var ev=require("events").EventEmitter;class b extends ev{constructor(n){super();let h=this;this.service=n;this.service.Request=function(c,k){"/"!=c.charAt(c.length-1)&&(c+="/");c+=k.method;var d={};!0===k.hasOwnProperty("parameters")&&(d=k.parameters);var q={},v=function(r){!0===r.payload.returnValue?(q=r.payload,k.onSuccess(q)):(q.returnValue=!1,q.errorCode=
r.payload.errorCode,q.errorText=r.payload.errorText,k.onFailure(q))};h.service&&h.service.call(c,d,v)};this.subsForEvents=this.service.subscribe("luna://com.webos.service.idcapmw.mwcommand/getAllEvents",{subscribe:!0});this.subsForEvents.on("response",function(c){c=c.payload;if("event"===c.command_id)h.on_event_received(c.command,c)})}on_event_received(n,h){this.emit(n,h)}request(n,h){if(null!==n&&""!==n&&void 0!==n&&!Array.isArray(h)&&void 0!==h)return new Promise((c,k)=>{h.onSuccess&&"function"===
typeof h.onSuccess&&(c=h.onSuccess);h.onFailure&&"function"===typeof h.onFailure&&(k=h.onFailure);this.service.Request("luna://com.webos.service.idcapmw.mwcommand",{method:"/callidcap",parameters:{command:n,parameters:h.parameters},onSuccess:function(d){d.result?(delete d.returnValue,delete d.result,delete d.command_id,c(d)):(delete d.returnValue,delete d.result,delete d.command_id,k(d))},onFailure:function(d){delete d.returnValue;delete d.result;delete d.command_id;k(d)}})})}}module.exports=b};
