// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Microsoft Software License Terms for the Azure Communications Services, Azure CPaaS, MICROSOFT AZURE COMMUNICATION CALLING EFFECTS
// See LICENSE file for license information.

import{DEFAULT_SUPPORTED_IMAGE_EXTENSIONS as e,IMAGE_BINARY_MAGIC_NUMBER_DICTIONARY as t}from"./5cb3d3.js";import{stringifyObject as a,wait as n}from"./cd7b0b.js";var __awaiter=function(e,t,a,n){function adopt(e){return e instanceof a?e:new a((function(t){t(e)}))}return new(a||(a=Promise))((function(a,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?a(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};class ImageLoader{constructor(e,t){this._logger=e,this._configProvider=t,this._loadedImage=null,this._loadedImageHasTransparentPixels=null}get loadedImage(){return this._loadedImage}get loadedImageHasTransparentPixels(){return this._loadedImageHasTransparentPixels}loadImage(t){return __awaiter(this,void 0,void 0,(function*(){try{this._loadedImage&&(this._loadedImage=null,this._loadedImageHasTransparentPixels=null);const n=yield window.fetch(t,{method:"GET",cache:"no-cache"}),r=yield n.blob(),i=r.type,o=yield r.arrayBuffer();if(!i.startsWith("image/"))throw new Error("URL is not an image");const s=this._extractImageExtension(i),d=e.some((e=>s===e)),l=this._verifyImageBinary(s,o);if(!d||!l)throw new Error(`Image extension is not currently supported. Supported formats are: ${a(e)}`);const c=URL.createObjectURL(r);return this._loadedImageHasTransparentPixels=yield this._imageHasTransparentPixels(c,s),this._loadedImage=c,this._loadedImage}catch(e){const t={code:"FailedToFetchImage",message:`Error fetching image from URL - ${a(e)}`};return Promise.reject(t)}}))}_extractImageExtension(e){return e.startsWith("image/")?e.replace("image/",""):""}_verifyImageBinary(e,a){var n;const r=new Uint8Array(a),i=null!==(n=t[e])&&void 0!==n?n:[];let o=!1;for(const e of i)if(o=e.every(((e,t)=>e===r[t])),o)break;return o}_imageHasTransparentPixels(e,t){return __awaiter(this,void 0,void 0,(function*(){if("png"!==t)return this._logger.debug("Image is not png"),null;const a=new Image;a.src=e;const r=n((()=>new Promise((e=>{a.onload=()=>{e()}}))),this._configProvider.config.videoEffects.imageTransparencyCheckTimeoutInMs);yield r;const i=document.createElement("canvas"),o=i.getContext("2d");if(!o)return this._logger.debug("Current environment does not support 2d canvas context. Cannot check if image has transparent pixels"),null;i.width=a.width,i.height=a.height,o.drawImage(a,0,0);const s=o.getImageData(0,0,i.width,i.height).data;for(let e=0;e<s.length;e+=4)if(s[e+3]<255)return this._logger.info("Provided image has transparent pixels"),!0;return!1}))}}export{ImageLoader};
