import{M as r,g as l,b as d,a as u}from"./fluent-player.js";const o=3e4;class m{constructor(t,e){this.player=t,this.mediaId=e,this.watchTracker=new r(t,{completionThreshold:100,mediaId:e,segmentUpdateInterVal:5}),this.dirty=!1,this.flushTimer=null,this.flushing=!1,this.lastSentPercentage=0,this.lastSentDuration=0,this._onPlay=this._handlePlay.bind(this),this._onPause=this._handlePause.bind(this),this._onEnded=this._handleEnded.bind(this),this._onVisibilityChange=this._handleVisibilityChange.bind(this),this._onBeforeUnload=this._handleBeforeUnload.bind(this),this._attachListeners()}_attachListeners(){this.player.addEventListener("play",this._onPlay),this.player.addEventListener("pause",this._onPause),this.player.addEventListener("ended",this._onEnded),document.addEventListener("visibilitychange",this._onVisibilityChange),window.addEventListener("beforeunload",this._onBeforeUnload)}_handlePlay(){this.dirty=!0,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}_handlePause(){this.scheduleFlush()}_handleEnded(){this.dirty=!0,Promise.resolve().then(()=>this.flush())}_handleVisibilityChange(){document.visibilityState==="hidden"&&this._finalizeAndFlush(!0)}_handleBeforeUnload(){this._finalizeAndFlush(!0)}_finalizeAndFlush(t){this.dirty&&(this.watchTracker&&(this.watchTracker.endTime=this.watchTracker.getPlayerCurrentTime(),this.watchTracker.addWatchedSegment()),this.flush(t))}scheduleFlush(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=setTimeout(()=>{this.flush()},o)}flush(t=!1){var a;if(!this.dirty||this.flushing||!this.mediaId)return;if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.flushing=!0,!((a=this.player)!=null&&a.duration)){this.flushing=!1;return}let e=Math.round(this.watchTracker.getWatchedPercentage()),i=Math.round(this.watchTracker.getTotalWatchedTime());if(e<=this.lastSentPercentage&&i<=this.lastSentDuration){this.flushing=!1,this.dirty=!1;return}const s={media_id:this.mediaId,duration:i,percentage:e},h=l();if(!h){this.flushing=!1;return}if(this.dirty=!1,t&&navigator.sendBeacon){const n=d("fluent_player_track_event",s);navigator.sendBeacon(h,n),this.lastSentPercentage=e,this.lastSentDuration=i,this.flushing=!1}else u("fluent_player_track_event",s).then(()=>{this.lastSentPercentage=e,this.lastSentDuration=i}).catch(()=>{this.dirty=!0}).finally(()=>{this.flushing=!1})}destroy(){this.dirty&&this._finalizeAndFlush(!0),this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.player.removeEventListener("play",this._onPlay),this.player.removeEventListener("pause",this._onPause),this.player.removeEventListener("ended",this._onEnded),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("beforeunload",this._onBeforeUnload),this.watchTracker&&(this.watchTracker.destroy(),this.watchTracker=null)}}export{m as default};
