/**
 * Copyright 2018 The Pennsylvania State University
 * @license Apache-2.0, see License.md for full text.
 */
import{css as e,html as t}from"../../lit/index.js";import{DDD as i}from"../d-d-d/d-d-d.js";import"../a11y-media-player/a11y-media-player.js";import{I18NMixin as a}from"../i18n-manager/lib/I18NMixin.js";import{IntersectionObserverMixin as r}from"../intersection-element/lib/IntersectionObserverMixin.js";import{MediaBehaviorsVideo as o}from"../media-behaviors/media-behaviors.js";import{SchemaBehaviors as s}from"../schema-behaviors/schema-behaviors.js";import{copyToClipboard as l}from"../utils/utils.js";class VideoPlayer extends(r(o(s(a(i))))){static get styles(){return[super.styles,e`
        :host {
          display: block;
          margin: var(--ddd-spacing-4) 0;
        }

        .video-caption {
          font-style: italic;
          margin: 0;
          padding: 8px;
        }
        a11y-media-player {
          box-shadow: var(--ddd-boxShadow-lg);
          --a11y-media-color: var(
            --video-player-color,
            var(--simple-colors-default-theme-accent-11, #111111)
          );

          --a11y-media-caption-color: var(
            --video-player-caption-color,
            var(--simple-colors-default-theme-grey-2, #eeeeee)
          );
          --a11y-media-bg-color: var(
            --video-player-bg-color,
            var(--simple-colors-default-theme-grey-2, #eeeeee)
          );

          --a11y-media-border-color: var(
            --video-player-border-color,
            var(--simple-colors-default-theme-accent-3, #dddddd)
          );

          --a11y-media-hover-color: var(
            --video-player-hover-color,
            var(--simple-colors-default-theme-accent-12, #000000)
          );

          --a11y-media-hover-bg-color: var(
            --video-player-hover-bg-color,
            var(--simple-colors-default-theme-accent-2, #eeeeee)
          );

          --a11y-media-accent-color: var(
            --video-player-accent-color,
            var(--simple-colors-default-theme-accent-9, #333333)
          );

          --a11y-media-faded-accent-color: var(
            --video-player-faded-accent-color,
            var(--simple-colors-default-theme-accent-8, #444444)
          );

          --a11y-media-disabled-color: var(
            --video-player-disabled-color,
            var(--simple-colors-default-theme-accent-5, #bbbbbb)
          );
        }
      `]}render(){return t` ${this.elementVisible?t`${this.isA11yMedia?t` <a11y-media-player
                accent-color="${this.accentColor}"
                ?audio-only="${this.audioOnly}"
                ?dark="${this.dark}"
                ?dark-transcript="${this.darkTranscript}"
                ?disable-interactive="${this.disableInteractive}"
                ?hide-timestamps="${this.hideTimestamps}"
                ?hide-transcript="${this.hideTranscript}"
                ?hide-youtube-link="${this.hideYoutubeLink}"
                id="${this.playerId}"
                @play="${this.playEvent}"
                @pause="${this.pauseEvent}"
                lang="${this.lang||"en"}"
                ?learning-mode="${this.learningMode}"
                ?linkable="${this.linkable}"
                preload="metadata"
                media-title="${this.mediaTitle||""}"
                .sources="${this.sourceProperties}"
                ?stand-alone="${this.standAlone}"
                sticky-corner="${this.stickyCorner||"none"}"
                thumbnail-src="${this.thumbnailSrc}"
                .tracks="${this.trackProperties}"
                .crossorigin="${this.crossorigin||"anonymous"}"
                .width="${this.width}"
                .height="${this.height}"
                youtube-id="${this.youtubeId}"
              >
              </a11y-media-player
              ><slot hidden></slot>`:t` <div
                class="responsive-video-container"
                .lang="${this.lang||"en"}"
              >
                ${this.sandboxed?t``:t` <webview
                      resource="${this.schemaResourceID}-video"
                      .src="${this.sourceData&&this.sourceData[0]&&this.sourceData[0].src||void 0}"
                      .width="${this.width||void 0}"
                      .height="${this.height||void 0}"
                      frameborder="0"
                    >
                    </webview>`}
                ${this.sandboxed||!this.iframed?t``:t`
                      <iframe
                        loading="lazy"
                        resource="${this.schemaResourceID}-video"
                        .src="${this.sourceData&&this.sourceData[0]&&this.sourceData[0].src||void 0}"
                        width="${this.width}"
                        height="${this.height}"
                        frameborder="0"
                        allow="autoplay; encrypted-media; fullscreen; picture-in-picture"
                      ></iframe>
                    `}
              </div>
              <div id="videocaption" class="video-caption">
                <p>
                  ${this.mediaTitle}
                  <span class="media-type print-only"
                    >(${this.t.embeddedMedia})</span
                  >
                </p>
                <slot name="caption"></slot>
              </div>
              <slot hidden></slot>`}`:""}`}static get haxProperties(){return{canScale:{min:50,step:25},designSystem:{primary:!0,card:!0},canEditSource:!0,gizmo:{title:"Video",description:"This can present video in a highly accessible manner regardless of source.",icon:"av:play-circle-filled",color:"red",tags:["Audio / Video","Media","youtube","watch","vimeo","twitch","mp4","webm","ogg","video-player","a11y","media-player"],handles:[{type:"video",type_exclusive:!0,source:"source",title:"caption",caption:"caption",description:"caption",color:"primaryColor"}],meta:{author:"HAXTheWeb core team",outlineDesigner:!0,anchorLabel:"mediaTitle"}},settings:{configure:[{property:"source",title:"Source",description:"The URL for this media.",inputMethod:"haxupload",noCamera:!0,noVoiceRecord:!0,validationType:"url"},{property:"mediaTitle",title:"Title",description:"Simple title for under video",inputMethod:"textfield",validationType:"text"},{property:"accentColor",title:"Accent color",description:"Select the accent color for the player.",inputMethod:"colorpicker"},{property:"track",title:"Closed captions",description:"The URL for the captions file.",inputMethod:"haxupload",noCamera:!0,noVoiceRecord:!0,validationType:"url"}],advanced:[{property:"thumbnailSrc",title:"Thumbnail image",description:"Optional. The URL for a thumbnail/poster image.",inputMethod:"haxupload",noVoiceRecord:!0,validationType:"url"},{property:"learningMode",title:"Enable learning mode",description:"Disables fast forward and rewind.",inputMethod:"boolean"},{property:"hideYoutubeLink",title:"Remove open on YouTube button",description:"Removes the button for opening the video on YouTube.",inputMethod:"boolean"},{property:"linkable",title:"Include a share link?",description:"Provides a link to share the video.",inputMethod:"boolean"}],developer:[{property:"crossorigin",title:"Crossorigin",description:"Indicates whether to use CORS.",inputMethod:"select",options:{"":"",anonymous:"anonymous","use-credentials":"use-credentials"}},{property:"allowBackgroundPlay",title:"Allow background playback",description:"Videos pause / play automatically when tab loses focus; this enables video to play without tab having focus",inputMethod:"boolean"},{property:"darkTranscript",title:"Dark theme for transcript",description:"Enable dark theme for the transcript.",inputMethod:"boolean"},{property:"disableInteractive",title:"Disable Interactive",description:"Disable interactive mode that makes transcript clickable.",inputMethod:"boolean"},{property:"hideTimestamps",title:"Hide timestamps",description:"Hide the time stamps on the transcript.",inputMethod:"boolean"},{property:"hideTranscript",title:"Hide Transcript",description:"Hide transcript by default.",inputMethod:"boolean"},{property:"lang",title:"Language",description:"Language of the media.",inputMethod:"textfield",validationType:"text"}]},saveOptions:{unsetAttributes:["__utils","__stand-alone","colors","playing","__forcePaused"]},demoSchema:[{tag:"video-player",properties:{source:"https://www.youtube.com/watch?v=LrS7dqokTLE","data-width":"75","data-margin":"center"},content:""}]}}static get properties(){return{...super.properties,sourceType:{type:String},accentColor:{type:String,attribute:"accent-color",reflect:!0},crossorigin:{type:String,attribute:"crossorigin",reflect:!0},dark:{type:Boolean,attribute:"dark",reflect:!0},darkTranscript:{type:Boolean},disableInteractive:{type:Boolean},height:{type:String},hideTimestamps:{type:Boolean,attribute:"hide-timestamps"},hideTranscript:{type:Boolean,reflect:!0,attribute:"hide-transcript"},id:{type:String,attribute:"id",reflect:!0},learningMode:{type:Boolean,attribute:"learning-mode"},lang:{type:String},linkable:{type:Boolean},mediaTitle:{type:String,attribute:"media-title",reflect:!0},hideYoutubeLink:{type:Boolean,attribute:"hide-youtube-link"},source:{type:String,reflect:!0},sources:{type:Array},sourceData:{type:Object},stickyCorner:{type:String,attribute:"sticky-corner",reflect:!0},track:{type:String},tracks:{type:Array},thumbnailSrc:{type:String,attribute:"thumbnail-src",reflect:!0},width:{type:String},playing:{type:Boolean,reflect:!0},allowBackgroundPlay:{type:Boolean,reflect:!0,attribute:"allow-background-play"}}}static get tag(){return"video-player"}querySelectorAll(e){return super.query&&super.querySelectorAll(e),[]}constructor(){super(),this.windowControllers=new AbortController,this.sourceType="",this.crossorigin="anonymous",this.dark=!1,this.darkTranscript=!1,this.disableInteractive=!1,this.hideTimestamps=!1,this.hideTranscript=!1,this.hideYoutubeLink=!1,this.lang="en",this.playing=!1,this.__setVisChange=!1,this.allowBackgroundPlay=!1,this.learningMode=!1,this.linkable=!1,this.sources=[],this.stickyCorner="none",this.tracks=[],this.source="",this.observer.observe(this,{childList:!0,subtree:!1}),this.t=this.t||{},this.t={...this.t,embeddedMedia:"embedded media"},this.registerLocalization({context:this,localesPath:new URL("./locales/video-player.es.json",import.meta.url).href+"/../",locales:["es"]})}disconnectedCallback(){this.__setVisChange&&(this.__setVisChange=!1,this.windowControllers.abort()),this.observer&&this.observer.disconnect&&this.observer.disconnect(),super.disconnectedCallback()}get html5(){return t`
      ${this.sourceData.filter((e=>"youtube"!==e.type)).map((e=>{t`
            <source
              .src="${e.src||void 0}"
              .type="${e.type||void 0}"
            />
          `}))}
      ${this.trackData.map((e=>{e.src,e.kind,e.label,e.lang}))}
    `}get iframed(){return!(!(this.sourceData&&this.sourceData.length>0&&void 0!==this.sourceData[0]&&globalThis.MediaBehaviors.Video._sourceIsIframe(this.sourceData[0].src))||this.sandboxed)}get isA11yMedia(){return!this.sandboxed&&("youtube"==this.sourceType||"local"==this.sourceType||this.sourceData.length<1)}get observer(){return new MutationObserver((()=>this.setSourceData()))}get sandboxed(){if(this.sourceData&&this.sourceData.length>0&&void 0!==typeof this.sourceData[0]&&globalThis.MediaBehaviors.Video._sourceIsIframe(this.sourceData[0].src)){if("function"==typeof globalThis.document.createElement("webview").reload)return!0}return!1}get sourceProperties(){let e="string"==typeof this.sources?JSON.parse(this.sources):(this.sources||[]).slice();return this.source&&e.unshift({src:this.source}),e&&e.length>0&&e.forEach((e=>{e.type=e.type||this._computeMediaType(e.src),e.src=this._computeSRC(e.src,e.type)})),e}get trackProperties(){let e="string"==typeof this.tracks?JSON.parse(this.tracks):(this.tracks||[]).slice();return this.track&&e.unshift({src:this.track}),e&&e.length>0&&e.forEach((e=>{e.srclang=e.srclang||this.lang,e.kind=e.kind||"subtitles",e.label=e.label||e.kind||e.lang})),e}get sourceData(){let e=(this.sourceProperties||[]).slice();return this.querySelectorAll("video source, audio source, iframe").forEach((e=>{this.sources.filter((t=>t.src===e.src)).length<1&&this.sources.unshift({src:e.src,type:e.type||this._computeMediaType(e.src)})})),e}get audioOnly(){return this.sourceData.filter((e=>e.type.indexOf("audio")>-1)).length>1}get standAlone(){return void 0===this.trackData||null===this.trackData||this.trackData.length<1}get trackData(){let e="string"==typeof this.tracks?(JSON.parse(this.tracks)||[]).slice():(this.tracks||[]).slice();return this.querySelectorAll("video track, audio track").forEach((e=>{if(this.tracks.filter((t=>t.src===e.src)).length<1){let t={src:e.src};e.lang&&(t.lang=e.lang),e.srclang&&(t.srclang=e.srclang),e.label&&(t.label=e.label),e.kind&&(t.kind=e.kind),this.tracks.unshift(t)}e.remove()})),void 0!==this.track&&null!==this.track&&""!==this.track&&e.push({src:this.track,srclang:this.lang,label:"en"===this.lang?"English":this.lang,kind:"subtitles"}),e}get youtubeId(){if(this.sourceData&&this.sourceData[0]&&"youtube"===this.sourceType)return this._computeSRC(this.sourceData[0].src).replace(/.*\/embed\//,"")}get playerId(){return`${this.id||this.schemaResourceID}-media`}_computeMediaType(e){let t="",findType=(i,a)=>{a.forEach((a=>{""===t&&void 0!==typeof e&&null!==e&&e.toLowerCase().indexOf("."+a)>-1&&(t=i+"/"+a)}))};return findType("audio",["aac","flac","mp3","oga","wav"]),findType("video",["mov","mp4","ogv","webm"]),t}_computeSRC(e,t){return null!==e&&void 0!==typeof e&&(t=t||globalThis.MediaBehaviors.Video.getVideoType(e),e=globalThis.MediaBehaviors.Video.cleanVideoSource(e,t),"vimeo"==t?(this.vimeoTitle?e+="?title=1":e+="?title=0",this.vimeoByline?e+="&byline=1":e+="&byline=0",this.vimeoPortrait?e+="&portrait=1":e+="&portrait=0"):"twitch"==t&&(e.indexOf("?")>-1?e+="&parent="+globalThis.location.hostname:e+="?parent="+globalThis.location.hostname)),e}haxHooks(){return{postProcessNodeToContent:"haxpostProcessNodeToContent",inlineContextMenu:"haxinlineContextMenu"}}haxinlineContextMenu(e){e.ceButtons=[{icon:"hax:anchor",callback:"haxClickTimeCode",label:"Copy current timecode"}]}haxClickTimeCode(e){return this.pause(),l(parseInt(this.currentTime)),!0}haxpostProcessNodeToContent(e){return e=(e=e.replace(' sources="[]",',"")).replace(' tracks="[]",',"")}setSourceData(){let e=this.source;this.source="",this.source=e,this.sourceData&&this.sourceData.length>0&&void 0!==this.sourceData[0]&&void 0!==this.sourceData[0].src&&(this.sourceType=globalThis.MediaBehaviors.Video.getVideoType(this.sourceData[0].src))}playEvent(e){this.playing=e.detail.__playing}pauseEvent(e){this.playing=e.detail.__playing}updated(e){super.updated(e),e.forEach(((e,t)=>{if("source"===t&&this.sourceType&&void 0!==e){let e=globalThis.MediaBehaviors.Video.getVideoType(this.sourceData[0].src);e!=this.sourceType&&(this.sourceType=e,this.elementVisible&&(this.elementVisible=!1,setTimeout((()=>{this.elementVisible=!0}),0)))}}))}firstUpdated(e){super.firstUpdated&&super.firstUpdated(e),e.forEach(((e,t)=>{"allowBackgroundPlay"===t&&this[t]&&this.__setVisChange?(this.__setVisChange=!1,this.windowControllers.abort()):"allowBackgroundPlay"!==t||this[t]||this.__setVisChange||(this.__setVisChange=!0,this.windowControllers=new AbortController,globalThis.document.addEventListener("visibilitychange",this._visChange.bind(this),{signal:this.windowControllers.signal}))})),this.sourceData&&this.sourceData.length>0&&void 0!==this.sourceData[0]&&void 0!==this.sourceData[0].src&&(this.sourceType=globalThis.MediaBehaviors.Video.getVideoType(this.sourceData[0].src))}get currentTime(){return this.shadowRoot?this.shadowRoot.querySelector("a11y-media-player").currentTime:0}restart(){this.pause(),this.seek(0),this.play()}pause(){this.shadowRoot&&this.shadowRoot.querySelector("a11y-media-player").__playing&&this.shadowRoot.querySelector("a11y-media-player").pause()}play(){this.shadowRoot&&!this.shadowRoot.querySelector("a11y-media-player").__playing&&this.shadowRoot.querySelector("a11y-media-player").play()}seek(e){this.shadowRoot&&(this.shadowRoot.querySelector("a11y-media-player").__playing||this.play(),setTimeout((()=>{this.shadowRoot.querySelector("a11y-media-player").seek(parseInt(e))}),0))}_visChange(e){setTimeout((()=>{"visible"===globalThis.document.visibilityState&&!this.playing&&this.__forcePaused?(this.__forcePaused=!1,this.shadowRoot.querySelector("a11y-media-player").togglePlay()):"hidden"===document.visibilityState&&this.playing?(this.__forcePaused=!0,this.shadowRoot.querySelector("a11y-media-player").togglePlay()):this.__forcePaused=!1}),500)}}customElements.define(VideoPlayer.tag,VideoPlayer);export{VideoPlayer};