/*************************************************************************
* ADOBE CONFIDENTIAL
* ___________________
*
*  Copyright 2015 Adobe Systems Incorporated
*  All Rights Reserved.
*
* NOTICE:  All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any.  The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and are protected by all applicable intellectual property laws,
* including trade secret and or copyright laws.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/
import{fileUtil as e}from"../viewer/fileUtil.js";import{getActiveTasks as t,setCloseRequested as r,wrapTask as a}from"./offscreenTaskManager.js";import{offscreenConfig as n}from"./offscrenUtil.js";import{saveGenAISidePanelRenderedHTML as o}from"./sidePanelCSSSRService.js";function i(e=5e3){let t,r;const a=new Promise((e,a)=>{t=e,r=a});return setTimeout(()=>{r(new Error("Operation timed out"))},e),{promise:a,resolve:t,reject:r}}let s;const c=new URLSearchParams(window.location.search).get("env")||"prod",d="iframe#user-subscription-iframe",l="iframe#floodgate-activity-iframe",m="iframe#user-state-iframe",f="iframe#ajs-worker-iframe",u="iframe#target-activity-iframe";let p,g,w;function b(e){const t=window.document.querySelector(e);t?.remove()}function R(e,t="ajs-worker-iframe"){const r=window.document.getElementById(t),a=n[c].acrobat_viewer_origin;r&&r.contentWindow.postMessage(e,a)}function I(e){if(!window.document.querySelector(d)&&e.cdnURL){const t=window.document;if(e.isCDNSignInEnabled){const t=new URL(e.signInURL);s=`${t}?main_op=fus`}else s=`${e.cdnURL}#/susi/fetchUserSubscription`;const r=t.createElement("iframe");r.setAttribute("src",s),r.setAttribute("id","user-subscription-iframe");t.getElementById("cdn-dnr-iframe").appendChild(r)}}function U(e){return new Promise((t,r)=>{const a=window.document.querySelector(l);if(a){if("callFloodgateAPI"!==e.main_op)return void t(a);b(l)}if(e.iframeURL){const r=window.document,a=new URL(e.iframeURL);a.searchParams.append("anonUserUUID",e.anonUserUUID),s=a;const n=r.createElement("iframe");n.setAttribute("src",s),n.setAttribute("id","floodgate-activity-iframe"),n.onload=()=>{t(n)},n.onerror=e=>{t(null)};r.getElementById("cdn-dnr-iframe").appendChild(n)}else r(new Error("signInURL is not provided"))})}function y(){0==t()?chrome.runtime.sendMessage({main_op:"closeOffscreenDocument",target:"background",tab:{id:""}}):setTimeout(y,100)}chrome.runtime.onMessage.addListener(function(e,t,r){if("offscreen"!==e.target)return!1;const l={getUserSubscriptions:a("getUserSubscriptions",I),getFileBuffer:a("getFileBuffer",async e=>{const t=await fetch(e.fileBufferBlob),r=await t.blob(),a=await new Response(r).arrayBuffer();R({main_op:"getFileBuffer",tabId:e.tabId,fileInfo:{fileBuffer:a,docLastOpenState:e.docLastOpenState}})}),closeIframeOfUserSubscription:a("closeIframeOfUserSubscription",()=>{b(d)}),getLinearizedRendition:a("getLinearizedRendition",e=>{R({main_op:"getLinearizedRendition",tabId:e.tabId,pdfURL:e.pdfURL,pdfSize:e.pdfSize,docLastOpenState:e.docLastOpenState})}),getFileSize:a("getFileSize",R),rrvLayerRemoved:a("rrvLayerRemoved",e=>{R({main_op:"rrvLayerRemoved",tabId:e.tabId})}),fgResponseFromCDN:a("fgResponseFromCDN",async e=>{e.main_op="handleFgResponseFromCDN";await U(e)&&R({main_op:"fgResponseFromCDN",response:e.response},"floodgate-activity-iframe")}),callFloodgateAPI:a("callFloodgateAPI",async e=>{e.main_op="callFloodgateAPI";await U(e)&&(p=i(),R({...e,main_op:"callFloodgateAPI"},"floodgate-activity-iframe"),p.promise.then(e=>{r({response:e})}).catch(e=>{r({response:void 0})}))}),getUserState:a("getUserState",async e=>{e.main_op="getUserState";var t;await(t=e,new Promise((e,r)=>{const a=window.document.querySelector(m);if(a)e(a);else if(t.iframeURL){const r=window.document,a=new URL(t.iframeURL);s=a;const n=r.createElement("iframe");n.setAttribute("src",s),n.setAttribute("id","user-state-iframe"),n.onload=()=>{e(n)},n.onerror=t=>{e(null)},r.getElementById("cdn-dnr-iframe").appendChild(n)}else r(new Error("iframeURL in user state detection is not found for requestId: "+t.requestId))}))&&(g=i(),R({...e},"user-state-iframe"),g.promise.then(e=>{r({response:e})}).catch(e=>{r({response:!1})}))}),createIframeToLoadAjsWorker:a("createIframeToLoadAjsWorker",async e=>{const t=await(a=e,new Promise(e=>{const t=a.env||c;s=n[t].ajs_worker_uri+"?callingApp="+window.location.host;const r=window.document.querySelector(f);if(r)return void e(r);const o=a.rrvEnabled,i=window.document;if(o){const t=i.createElement("iframe");t.setAttribute("src",s),t.setAttribute("id","ajs-worker-iframe"),t.onload=()=>{e(t)},t.onerror=()=>{e(null)},i.getElementById("cdn-dnr-iframe").appendChild(t)}else e(null)}));var a;r({iframeLoaded:!!t})}),fetchImageBlobURL:a("fetchImageBlobURL",async e=>{try{const t=await fetch(e.imgUrl);if(!t.ok)return void r({error:`Response not in 2xx range. Status: ${t.status}`});const a=await t.blob(),n=URL.createObjectURL(new Blob([a],{type:a.type||"application/octet-stream"}));r({blobUrl:n})}catch(e){r({error:e.message})}}),revokeImageBlobURL:a("revokeImageBlobURL",e=>{URL.revokeObjectURL(e.blobUrl)}),callTargetAPI:a("callTargetAPI",async e=>{e.main_op="callTargetAPI";await new Promise((e,t)=>{const r=window.document.querySelector(u);if(r)return void e(r);const a=window.document,o=new URL(n[c].target_uri);o.searchParams.append("ao","false"),o.searchParams.append("la","true"),o.searchParams.append("callingApp",window.location.host),s=o;const i=a.createElement("iframe");i.setAttribute("src",s),i.setAttribute("id","target-activity-iframe"),i.onload=()=>{e(i)},i.onerror=t=>{e(null)},a.getElementById("cdn-dnr-iframe").appendChild(i)})&&(w=i(),R({...e,main_op:"callTargetAPI",mboxes:e.mboxes},"target-activity-iframe"),w.promise.then(e=>{r(e)}).catch(e=>{r({targetResponse:{},error:e.message})}))}),saveGenAIPanelRender:a("saveGenAIPanelRender",async e=>{await o(e)})};if(!l[e.main_op])return console.warn(`Unexpected message type received: '${e.main_op}'.`),!1;(async()=>{await l[e.main_op](e)})();return!0}),window.addEventListener("message",function(t){try{if(t.origin!==new URL(s).origin)return;const n=t.data;"lastUserGuid"===n.type&&(n.main_op="updateSignInStatus",delete n.type);const o={userSubscriptions:a("userSubscriptions",()=>{chrome.runtime.sendMessage({...n,target:"background",tab:{id:""}})}),updateSignInStatus:a("updateSignInStatus",()=>{chrome.runtime.sendMessage({...n,target:"background",tab:{id:""}})}),closeOffscreenDocument:()=>{r(!0),y()},getFileBufferRange:a("getFileBufferRange",async()=>{try{const t=await e.getFileBufferRange({url:n.pdfURL},n.range),r=await new Response(t.buffer).arrayBuffer();R({main_op:"acceptRangesBuffer",tabId:n.tabId,fileBuffer:r,rangeKey:`${n.range.start}-${n.range.end}`,fileSize:t.fileSize})}catch{R({main_op:"acceptRangesBuffer",tabId:n.tabId,fileBuffer:-1,rangeKey:`${n.range.start}-${n.range.end}`,fileSize:-1})}}),rapidRenditionResponse:a("rapidRenditionResponse",()=>{chrome.runtime.sendMessage({...n,target:"background",tab:{id:n.tabId}})}),rapidRenditionError:a("rapidRenditionError",()=>{chrome.runtime.sendMessage({...n,target:"background",tab:{id:n.tabId}})}),callFloodgateAPIResponse:a("callFloodgateAPIResponse",e=>{p.resolve(e.data)}),getUserStateResponse:a("getUserStateResponse",e=>{g.resolve(e.data)}),callTargetAPIResponse:a("callTargetAPIResponse",e=>{w.resolve(e.data)})};o[n?.main_op]&&o[n.main_op](t)}catch(e){console.error("Error in handling CDN event",e)}});