/**
 * Copyright 2019 The Pennsylvania State University
 * @license Apache-2.0, see License.md for full text.
 */
import{LitElement as e,html as t,css as i}from"../../lit/index.js";import"../es-global-bridge/es-global-bridge.js";globalThis.__H5PBridgeTimeOut=function(){setTimeout((function(){globalThis.H5P.init()}),500)};class H5PElement extends e{static get styles(){return[i`
        :host {
          display: block;
        }
      `]}render(){return t` ${this.source?t`<div
          class="h5p-container"
          data-content-id="wrapper-${this.contentId}"
        ></div>`:t`<h5p-wrapped-element><slot></slot></h5p-wrapped-element>`}`}static get haxProperties(){return new URL(`./lib/${this.tag}.haxProperties.json`,import.meta.url).href}static get properties(){return{...super.properties,source:{name:"source",type:String}}}static get tag(){return"h5p-element"}constructor(){super(),this.contentId=this.generateUUID()}createRenderRoot(){return this.source?this:super.createRenderRoot()}async H5PDepsLoader(){this.windowControllers=new AbortController;const e=new URL("./lib/h5p-resizer.js",import.meta.url).href+"/../";this.h5pJSDeps=[e+"h5p-resizer.js",e+"h5p/js/jquery.js",e+"h5p/js/h5p.js",e+"h5p/js/h5p-event-dispatcher.js",e+"h5p/js/h5p-content-type.js",e+"h5p/js/h5p-action-bar.js",e+"h5p/js/h5p-confirmation-dialog.js",e+"h5p/js/h5p-x-api-event.js",e+"h5p/js/h5p-x-api.js"],this.__h5pDepsLength=this.h5pJSDeps.length-1,await globalThis.ESGlobalBridge.requestAvailability().load("h5p-jquery",e+"h5p/js/jquery.js"),globalThis.addEventListener("es-bridge-h5p-jquery-loaded",this.h5pJqueryReady.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("es-bridge-h5p-"+this.__h5pDepsLength+"-loaded",this.h5pReadyCallback.bind(this),{signal:this.windowControllers.signal})}generateUUID(){return"item-sss-ss-ss".replace(/s/g,this._uuidPart)}_uuidPart(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}firstUpdated(e){super.firstUpdated&&super.firstUpdated(e),this.source&&!0===globalThis.ESGlobalBridge.requestAvailability().imports["h5p-"+this.__h5pDepsLength]&&this.contentId&&this.setupH5P(this.contentId),this.source||import("./lib/h5p-wrapped-element.js")}async h5pJqueryReady(e){for(var t in this.h5pJSDeps)await globalThis.ESGlobalBridge.requestAvailability().load("h5p-"+t,this.h5pJSDeps[t])}h5pReadyCallback(e){this.contentId&&this.setupH5P(this.contentId)}async setupH5P(e=1,t={}){t=Object.assign(t,{frame:t.frame=!1,copyright:t.copyright=!1,embed:t.embed=!1,download:t.download=!1,icon:t.icon=!1,export:t.export=!1});const i=new URL("./lib/h5p-element.js",import.meta.url).href+"/../";H5PIntegration.core={styles:[i+"h5p/styles/h5p.css",i+"h5p/styles/h5p-confirmation-dialog.css",i+"h5p/styles/h5p-core-button.css"],scripts:this.h5pJSDeps};let s=globalThis.document.createRange().createContextualFragment(`\n     <div class="h5p-iframe-wrapper" style="background-color:#DDD;">\n       <iframe id="h5p-iframe-${e}" class="h5p-iframe" data-content-id="${e}" style="width: 100%; height: 100%; border: none; display: block;" src="about:blank" frameBorder="0"></iframe>\n     </div>\n     `);if(this.querySelector('[data-content-id="wrapper-'+this.contentId+'"')&&this.querySelector('[data-content-id="wrapper-'+this.contentId+'"').appendChild(s),this.source){let i=new H5PStandalone(e,this.source,t);await i.init(),globalThis.__H5PBridgeTimeOut&&(clearTimeout(globalThis.__H5PBridgeTimeOut),globalThis.__H5PBridgeTimeOut())}return!0}connectedCallback(){super.connectedCallback(),this.H5PDepsLoader()}disconnectedCallback(){this.windowControllers.abort(),super.disconnectedCallback()}}customElements.define("h5p-element",H5PElement),globalThis.H5P=globalThis.H5P||{},globalThis.H5PIntegration=globalThis.H5PIntegration||{},H5PIntegration.l10n={H5P:{advancedHelp:"Include this script on your website if you want dynamic sizing of the embedded content:",author:"Author",by:"by",close:"Close",contentChanged:"This content has changed since you last used it.",copyrightInformation:"Rights of use",copyrights:"Rights of use",copyrightsDescription:"View copyright information for this content.",disableFullscreen:"Disable fullscreen",download:"Download",downloadDescription:"Download this content as a H5P file.",embed:"Embed",embedDescription:"View the embed code for this content.",fullscreen:"Fullscreen",h5pDescription:"Visit H5P.org to check out more cool content.",hideAdvanced:"Hide advanced",license:"License",noCopyrights:"No copyright information available for this content.",showAdvanced:"Show advanced",showLess:"Show less",showMore:"Show more",size:"Size",source:"Source",startingOver:"You'll be starting over.",subLevel:"Sublevel",thumbnail:"Thumbnail",title:"Title",year:"Year"}};class H5PStandalone{constructor(e=1,t,i){return this.id=e,this.path=t,this.displayOptions=i,!0}getJSONPromise(e){return fetch(e).then((function(e){return e.json()}))}async init(){this.h5p=await this.getJSONPromise(`${this.path}/h5p.json`),this.content=JSON.stringify(await this.getJSONPromise(`${this.path}/content/content.json`)),globalThis.H5PIntegration.pathIncludesVersion=this.pathIncludesVersion=await this.checkIfPathIncludesVersion(),this.mainLibrary=await this.findMainLibrary();const e=await this.findAllDependencies(),{styles:t,scripts:i}=await this.sortDependencies(e);return H5PIntegration.url=this.path,H5PIntegration.contents=H5PIntegration.contents?H5PIntegration.contents:{},H5PIntegration.contents["cid-"+this.id]={library:`${this.mainLibrary.machineName} ${this.mainLibrary.majorVersion}.${this.mainLibrary.minorVersion}`,jsonContent:this.content,styles:t,scripts:i,displayOptions:this.displayOptions},!0}async checkIfPathIncludesVersion(){let e,t=this.h5p.preloadedDependencies[0],i=t.machineName+"-"+t.majorVersion+"."+t.minorVersion;try{await this.getJSONPromise(`${this.path}/${i}/library.json`),e=!0}catch(t){e=!1}return e}libraryPath(e){return e.machineName+(this.pathIncludesVersion?"-"+e.majorVersion+"."+e.minorVersion:"")}findMainLibrary(){const e=this.h5p.preloadedDependencies.find((e=>e.machineName===this.h5p.mainLibrary));return this.mainLibraryPath=this.h5p.mainLibrary+(this.pathIncludesVersion?"-"+e.majorVersion+"."+e.minorVersion:""),this.getJSONPromise(`${this.path}/${this.mainLibraryPath}/library.json`)}findAllDependencies(){const e=this.h5p.preloadedDependencies.map((e=>this.libraryPath(e)));return this.loadDependencies(e,[])}async loadDependencies(e,t){let i=t,s=[],r=await Promise.all(e.map((e=>this.findLibraryDependencies(e))));return r.forEach((e=>{i.push(e),e.dependencies.forEach((e=>{i.find((t=>t.libraryPath===e))||r.find((t=>t.libraryPath===e))||s.push(e)}))})),s.length>0?this.loadDependencies(s,i):i}async findLibraryDependencies(e){const t=await this.getJSONPromise(`${this.path}/${e}/library.json`),i=this.libraryPath(t);let s=[];return t.preloadedDependencies&&(s=t.preloadedDependencies.map((e=>this.libraryPath(e)))),{libraryPath:i,dependencies:s,preloadedCss:t.preloadedCss,preloadedJs:t.preloadedJs}}async sortDependencies(e){const t=new Toposort;let i={},s={};e.forEach((e=>{t.add(e.libraryPath,e.dependencies),e.preloadedCss&&(i[e.libraryPath]=i[e.libraryPath]?i[e.libraryPath]:[],e.preloadedCss.forEach((t=>{i[e.libraryPath].push(`${this.path}/${e.libraryPath}/${t.path}`)}))),e.preloadedJs&&(s[e.libraryPath]=s[e.libraryPath]?s[e.libraryPath]:[],e.preloadedJs.forEach((t=>{s[e.libraryPath].push(`${this.path}/${e.libraryPath}/${t.path}`)})))}));let r=[],n=[];return t.sort().reverse().forEach((function(e){Array.prototype.push.apply(r,i[e]),Array.prototype.push.apply(n,s[e])})),Array.prototype.push.apply(r,this.mainLibrary.preloadedCss.map((e=>`${this.path}/${this.mainLibraryPath}/${e.path}`))),Array.prototype.push.apply(n,this.mainLibrary.preloadedJs.map((e=>`${this.path}/${this.mainLibraryPath}/${e.path}`))),{styles:r,scripts:n}}}class Toposort{constructor(){this.edges=[]}add(e,t){if("string"!=typeof e||!e)throw new TypeError("Dependent name must be given as a not empty string");if((t=Array.isArray(t)?t:[t]).length>0)for(let i of t){if("string"!=typeof i||!i)throw new TypeError("Dependency name must be given as a not empty string");this.edges.push([e,i])}else this.edges.push([e]);return this}sort(){let e=[];for(let t of this.edges)for(let i of t)-1===e.indexOf(i)&&e.push(i);let t=e.length,i=new Array(e.length);var visit=(s,r)=>{if(0!==r.length&&-1!==r.indexOf(s))throw new Error(`Cyclic dependency found. ${s} is dependent of itself.\nDependency chain: ${r.join(" -> ")} => ${s}`);let n=e.indexOf(s);if(-1!==n){let a=!1;e[n]=!1;for(let e of this.edges)e[0]===s&&(a=a||r.concat([s]),visit(e[1],a));i[--t]=s}};for(let s=0;s<e.length;s++){let r=e[s];if(!1!==r){e[s]=!1;for(let e of this.edges)e[0]===r&&visit(e[1],[r]);i[--t]=r}}return i}clear(){return this.edges=[],this}}export{H5PElement,H5PStandalone,Toposort};