//!wrt $BSPEC:{"icn":"apps/iexploder","cpr":"Copyright (C) Windows 96 Team 2023.","dsc":"InternetE browser application.","frn":"InternetE","ver":1,"ssy":"gui"}

const{WindowParams:WindowParams,sysConf:SCM}=w96,{SaveFileDialog:SaveFileDialog,OpenFileDialog:OpenFileDialog,DialogCreator:DialogCreator,MenuBar:MenuBar,Theme:Theme}=w96.ui,{ToolBar:ToolBar,TabControl:TabControl,GroupBox:GroupBox}=w96.ui.components,{INI:INI}=w96.util,{execCmd:execCmd,execFile:execFile}=w96.sys,CONFIG={homepage:"https://collabsysos.xyz",searchEngine:"about:blank?placeholder&q=%SEARCH_QUERY%"},systemUrls=[{url:"https://collabsysos.xyz",title:"CollabSysOS.XYZ",redir:"/system/data/iexploder/syspages/start",import_sys:!0}];function showInternetOptionsWnd(t){const e=t.createWindow({title:"Internet Options",bodyClass:"applet-base",body:'<div class="tabc"></div>\n        <div class="buttons">\n            <button class="w96-button apply" disabled>Apply</button>\n            <button class="w96-button cancel">Cancel</button>\n            <button class="w96-button ok">OK</button>\n        </div>',icon:null,initialWidth:406,initialHeight:452,controlBoxStyle:"WS_CBX_CLOSE",resizable:!1,taskbar:!1},!1),i={...CONFIG,...t.config},a=e.getBodyContainer();a.classList.add("wnd-ie-inet-options");const s=new TabControl;return s.openPage(s.addPage("General",(async e=>{e.style.padding="10px",e.style.boxSizing="border-box",e.innerHTML='<div class="grpbx1"></div>\n        <div class="grpbx2"></div>';const a=new GroupBox({title:"Home page",body:`<div class="icon-box hp">\n                        <div class="icon" style="background-image: url(${await Theme.getIconUrl("misc/homepage")});"></div>\n                        <div class="text">\n                            <div>You can change which page to use for your home page.</div>\n                            <div class="addr-box"><span>Address: </span> <input type="text" class="w96-textbox"></div>\n\n                            <div class="ic-buttons">\n                                <button class="w96-button hp-current">Use Current</button>\n                                <button class="w96-button hp-default">Use Default</button>\n                                <button class="w96-button hp-blank">Use Blank</button>\n                            </div>\n                        </div>\n                    </div>`}).getElement(),s=a.querySelector(".hp input");a.querySelector(".hp-current").addEventListener("click",(()=>{s.value=t.lastUrl,i.homepage=s.value})),a.querySelector(".hp-default").addEventListener("click",(()=>{s.value=CONFIG.homepage,i.homepage=s.value})),a.querySelector(".hp-blank").addEventListener("click",(()=>{s.value="about:blank",i.homepage=s.value})),s.value=i.homepage;const n=new GroupBox({title:"History",body:`<div class="icon-box hist">\n                <div class="icon" style="background-image: url(${await Theme.getIconUrl("misc/history")});"></div>\n                <div class="text">\n                    <div>InternetE keeps track of which sites you have visited.<br><br>\n                    To clear this history, click the button below.</div>\n\n                    <div class="ic-buttons">\n                        <button class="w96-button hist-clean">Clear History</button>\n                    </div>\n                </div>\n            </div>`}).getElement();n.querySelector(".hist-clean").addEventListener("click",(()=>t.clearHistory())),e.querySelector(".grpbx1").replaceWith(a),e.querySelector(".grpbx2").replaceWith(n)}))),a.querySelector(".tabc").replaceWith(s.getElement()),a.querySelector("button.cancel").addEventListener("click",(()=>e.close())),a.querySelector("button.ok").addEventListener("click",(()=>{t.config={...t.config,...i},t.commitCurrentConfiguration(),e.close()})),e.show(),e}function formatUrl(t){let e=t;return t.startsWith("about:")||t.startsWith("/")||e.startsWith("https://")||e.startsWith("http://")||(e="https://"+e),e}class InternetEApplication extends WApplication{constructor(){super(),this.ofdLastDir="C:/user",this.lastUrl="",this.favorites=[],this.history=[],this.persistentHistory=[],this.historyPos=-1,this.uiState={nav:{btnFwd:null,btnBack:null}}}async main(t){super.main(t),await this.createUI(t)}async loadFavorites(){await FS.exists("C:/user/links")||await FS.mkdir("C:/user/links"),this.favorites=[];for(let t of await FS.readdir("C:/user/links")){if(!await FS.isFile(t)||".url"!==FSUtil.getExtension(t).toLowerCase())continue;const e=await FSUtil.fname(t);try{this.favorites.push({title:e.substring(0,e.length-4),url:INI.parse(await FS.readstr(t)).InternetShortcut.URL})}catch(e){console.warn(`Unable to parse favorite ${t}`,e)}}}clearHistory(){this.history=[],this.persistentHistory=[],this.historyPos=-1,this.updateNavButtons()}setupMenuBar(){const t=this.mainwnd.getBodyContainer(),e=new MenuBar;e.addRoot("File",[{type:"submenu",label:"New",items:[{type:"normal",label:"Window",onclick:()=>{execCmd("internete",[])}}]},{type:"normal",label:"Open",onclick:()=>this.showOpenUI()},{type:"normal",label:"Save",onclick:()=>this.showSaveUI(),disabled:!0},{type:"separator"},{type:"normal",label:"Close",onclick:()=>this.terminate()}],!1),e.addRoot("View",[{type:"normal",label:"Refresh",onclick:()=>this.navigate(this.lastUrl)},{type:"separator"},{type:"normal",label:"Internet Options",onclick:()=>showInternetOptionsWnd(this)}]),e.addRoot("Go",[{type:"normal",label:"Back",onclick:()=>this.goBack()},{type:"normal",label:"Forward",onclick:()=>this.goForward()},{type:"separator",label:""},{type:"normal",label:"Home Page",onclick:()=>this.navigate(this.config.homepage)}]),e.addRoot("Favorites",[{type:"normal",label:"Add to Favorites...",onclick:()=>this.showAddFavoriteUI()},{type:"normal",label:"Organize Favorites...",onclick:()=>{execFile("C:/user/links")}}]),e.addRoot("Help",[{type:"normal",label:"About",onclick:()=>{DialogCreator.alert('<span class="bold-noaa">InternetE</span><br>Version 2.0<br>',{title:"About InternetE",icon:"info"})}}]),t.querySelector(".appbar").replaceWith(e.getMenuDiv())}async setupToolBar(){const t=this.mainwnd.getBodyContainer(),e=new ToolBar,i=e.addItem({name:"back",text:"Back",imageUrl:await Theme.getIconUrl("actions/back","24x24"),onclick:()=>{a.el.removeAttribute("disabled"),this.goBack(),0===this.historyPos&&i.el.setAttribute("disabled","true")}});i.el.setAttribute("disabled","true"),this.uiState.nav.btnBack=i;const a=e.addItem({name:"forward",text:"Forward",imageUrl:await Theme.getIconUrl("actions/forward","24x24"),onclick:()=>{i.el.removeAttribute("disabled"),this.goForward(),this.historyPos+1===this.history.length&&a.el.setAttribute("disabled","true")}});a.el.setAttribute("disabled","true"),this.uiState.nav.btnFwd=a,e.addItem({name:"stop",text:"Stop",imageUrl:await Theme.getIconUrl("actions/stop","24x24"),onclick:()=>this.navigate("about:blank")}),e.addItem({name:"refresh",text:"Refresh",imageUrl:await Theme.getIconUrl("actions/refresh","24x24"),onclick:()=>this.navigate(this.lastUrl)}),e.addItem({name:"home",text:"Home",imageUrl:await Theme.getIconUrl("actions/home","24x24"),onclick:()=>this.navigate(this.config.homepage)}),e.addSeparator(),e.addItem({name:"search",text:"Search",imageUrl:await Theme.getIconUrl("actions/search","24x24"),onclick:()=>this.showSearchUI()}),e.addItem({name:"favorites",text:"Favorites",imageUrl:await Theme.getIconUrl("actions/favorites","24x24"),onclick:()=>this.showUtilityPane("favorites")}),e.addItem({name:"history",text:"History",imageUrl:await Theme.getIconUrl("actions/history","24x24"),onclick:()=>this.showUtilityPane("history")}),e.addSeparator(),e.addItem({name:"fullscreen",text:"Fullscreen",imageUrl:await Theme.getIconUrl("actions/fullscreen","24x24"),onclick:()=>{this.appFrame.requestFullscreen()}}),t.querySelector(".toolbar").replaceWith(e.getElement())}async createUI(t){this.mainwnd=this.createWindow({bodyClass:"internete-app",body:'<div class="w96-ui-inset">\n                <div class="appbar"></div>\n                <div class="toolbar"></div>\n                <div class="nav-box">\n                    <div class="text">Address:</div>\n                    <input class="w96-textbox" type="text">\n                    \x3c!-- <button class="w96-button go">Go</button> --\x3e\n                </div>\n            </div>\n            <div class="combo-panel">\n                <div class="left"></div>\n                <div class="right">\n                    <iframe class="content"></iframe>\n                </div>\n            </div>\n            <div class="w96-footer">\n                <div class="cell status">\n                    Done\n                </div>\n                <div class="cell zone">\n                    Internet Zone\n                </div>\n            </div>',initialHeight:500,initialWidth:640,title:"Untitled - InternetE",icon:await Theme.getIconUrl("apps/iexploder","16x16"),taskbar:!0},!0),this.config={...CONFIG,...SCM.get("Software/InternetE")},null==SCM.get("Software/InternetE")&&await this.commitCurrentConfiguration(),this.setupMenuBar(),this.setupToolBar(),this.setupIframe(),await this.loadFavorites();const e=this.mainwnd.getBodyContainer();e.querySelector(".combo-panel>.left").style.display="none",this.appFrame=e.querySelector("iframe"),this.navBox=e.querySelector(".nav-box>input"),this.navBox.addEventListener("keydown",(t=>{"Enter"==t.key&&this.navigate(this.navBox.value)})),this.mainwnd.show(),null!=t[1]?this.navigate(t[1]):this.navigate(this.config.homepage)}async commitCurrentConfiguration(){await SCM.setAndSync("Software/InternetE",this.config)}showAddFavoriteUI(){return DialogCreator.prompt(`Please enter the new link name for ${this.lastUrl}`,{title:"Add Favorite"},(t=>{t&&""!=t.trim()&&FS.writestr(`C:/user/links/${t}.url`,INI.stringify({InternetShortcut:{URL:formatUrl(this.lastUrl)}})).then((async()=>this.showUtilityPane("favorites")))}))}setupIframe(){const t=this.mainwnd.getBodyContainer(),e=t.querySelector("iframe"),i=t.querySelector(".cell.status");e.addEventListener("load",(()=>{i.textContent="Done"}))}async showUtilityPane(t){await this.loadFavorites();const e=this.mainwnd.getBodyContainer().querySelector(".combo-panel>.left");e.style.display="";const i=document.createElement("div");for(i.classList.add("pane-container","w96-ui-inset");e.firstChild;)e.removeChild(e.firstChild);const a=document.createElement("div");a.classList.add("pane-bar");const s=document.createElement("div");s.classList.add("title"),a.appendChild(s);const n=document.createElement("div");n.classList.add("close"),n.onclick=()=>{for(;e.firstChild;)e.removeChild(e.firstChild);e.style.display="none"},a.appendChild(n),i.appendChild(a);const o=document.createElement("div");switch(o.classList.add("content"),t){case"favorites":i.classList.add("favorites"),s.textContent="Favorites";for(let t of this.favorites){const e=document.createElement("div");e.classList.add("favorite");const i=document.createElement("div");i.classList.add("image"),Theme.getIconUrl("mime/html","16x16").then((t=>i.style.backgroundImage=`url(${t})`)),e.appendChild(i);const a=document.createElement("div");a.classList.add("text"),a.textContent=t.title,e.appendChild(a),e.addEventListener("click",(()=>{o.querySelectorAll(".favorite.active").forEach((t=>t.classList.remove("active"))),e.classList.add("active"),this.navigate(t.url)})),o.appendChild(e)}break;case"history":i.classList.add("favorites"),s.textContent="History";for(let t=this.persistentHistory.length-1;t>=0;t--){const e=this.persistentHistory[t],i=document.createElement("div");i.classList.add("favorite");const a=document.createElement("div");a.classList.add("image"),Theme.getIconUrl("mime/html","16x16").then((t=>a.style.backgroundImage=`url(${t})`)),i.appendChild(a);const s=document.createElement("div");s.classList.add("text"),s.textContent=e,i.appendChild(s),i.addEventListener("click",(()=>{o.querySelectorAll(".favorite.active").forEach((t=>t.classList.remove("active"))),i.classList.add("active"),this.navigate(e)})),o.appendChild(i)}}i.appendChild(o),e.appendChild(i)}async navigate(t,e={}){const i={quiet:!1,addHistory:!0,...e};if(this.lastUrl=t,i.quiet||Theme.playSound("navigate"),this.mainwnd.getBodyContainer().querySelector(".cell.status").innerText=`Loading ${t}`,i.addHistory&&(this.historyPos+1!=this.history.length&&(this.history=this.history.slice(0,this.historyPos+1)),this.history[this.history.length-1]!==t&&(this.history.push(t),this.historyPos++),this.persistentHistory[this.persistentHistory.length-1]!==t&&this.persistentHistory.push(t)),await FS.exists(t)){if(t.toLowerCase().endsWith(".url")){const e=INI.parse(await FS.readstr(t));if(e.InternetShortcut&&e.InternetShortcut.URL)return this.navigate(e.InternetShortcut.URL,{quiet:!0})}const e=FSUtil.deconstructFullPath(t);return this.navigate(`/_/${e.prefix[0]}/${t.substring(3)}`,{quiet:!0})}const a=systemUrls.find((e=>e.url==t));if(this.appFrame.onload=()=>{},a)return a.title?this.mainwnd.setTitle(a.title+" - InternetE"):this.mainwnd.setTitle(t+" - InternetE"),this.navBox.value=t,a.import_sys&&(this.appFrame.onload=()=>{this.appFrame.contentWindow.w96=w96}),void(a.body?this.appFrame.src="data:text/html;base64,"+btoa(a.body):this.appFrame.src=a.redir);const s=formatUrl(t);this.mainwnd.setTitle(s+" - InternetE"),this.navBox.value=s,this.appFrame.src=s,this.updateNavButtons()}updateNavButtons(){this.historyPos+1!=this.history.length&&this.uiState.nav.btnFwd&&this.uiState.nav.btnFwd.el.setAttribute("disabled","true"),0!==this.history.length&&this.uiState.nav.btnBack&&this.uiState.nav.btnBack.el.removeAttribute("disabled")}goBack(t=!0){if(this.history.length>0&&this.historyPos-1>=0){let e=this.history[--this.historyPos];return t&&this.navigate(e),e}}goForward(t=!0){if(this.history.length>0&&this.historyPos+1<this.history.length){let e=this.history[++this.historyPos];return t&&this.navigate(e),e}}showSaveUI(){this.crossIfrCheck()||DialogCreator.alert("Unable to save document due to CORS.",{icon:"error",title:"InternetE"})}showOpenUI(){new OpenFileDialog(this.ofdLastDir,["html","htm","url"],(t=>{t&&(this.navigate(t),this.mainwnd.activate(),this.ofdLastDir=FSUtil.getParentPath(t))})).show()}showSearchUI(){return DialogCreator.prompt("Please enter your search query.",{title:"Search with search engine"},(t=>{t&&""!=t.trim()&&this.navigate(this.config.searchEngine.replace("%SEARCH_QUERY%",t))}))}crossIfrCheck(){try{return Boolean(this.appFrame.contentDocument)}catch(t){return!1}}ontermination(){this.mainwnd=null,this.appFrame=null,this.navBox=null,this.uiState=null,super.ontermination()}}

return await WApplication.execAsync(new InternetEApplication(), this.boxedEnv.args, this);