/*************************************************************************
* 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.
**************************************************************************/
const ATTRIBUTION_HIGHLIGHTING_STATUS={SUCCESS:"Success",ERROR:"Error"};class AttributionManager{constructor(){if(AttributionManager.instance)return AttributionManager.instance;AttributionManager.instance=this,this.highlight=new Highlight,this.registerSidepanelCloseListener();const t=document.createElement("style");t.innerHTML="\n            @media (prefers-color-scheme: dark) {\n                ::highlight(search-results) {\n                    background-color: #5258E4;\n                    color: white;\n                }\n            }\n\n            @media (prefers-color-scheme: light) {\n                ::highlight(search-results) {\n                    background-color: #D3D5FF;\n                    color: black;\n                }\n            }\n        ",document.head.appendChild(t)}registerSidepanelCloseListener(){chrome.runtime.onMessage.addListener(async t=>{if("sidepanel_closed"===t.action)this.removeHighlights()})}getNodeFromXPath(t){return(new XPathEvaluator).evaluate(t,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}isRangeVisible(t){const e=t.getBoundingClientRect();if(e.width<=0||e.height<=0)return!1;let n=t.startContainer.nodeType===Node.ELEMENT_NODE?t.startContainer:t.startContainer.parentElement;for(;n;){if("0"===window.getComputedStyle(n).opacity)return!1;n=n.parentElement}return!0}logAttributionSuccessPercentage(t="",e=""){try{let n=0;if(t&&e){const r=t.match(/"[^"]+"|[\w]+/g)||[],o=e.match(/"[^"]+"|[\w]+/g)||[],i=r.length,s=o.length;if(i&&s){const t=Array(i+1).fill(null).map(()=>Array(s+1).fill(0));for(let e=1;e<=i;e++)for(let n=1;n<=s;n++)r[e-1]===o[n-1]?t[e][n]=t[e-1][n-1]+1:t[e][n]=Math.max(t[e-1][n],t[e][n-1]);const e=t[i][s];n=(e/Math.max(i,s)*100).toFixed(2)}}chrome.runtime.sendMessage({main_op:"log-info",log:{message:"[Attribution Info]: Matching percentage of X path content and bound content",contentMatchPercentage:n,xPathContent:t,boundContent:e}})}catch(t){chrome.runtime.sendMessage({main_op:"log-error",log:{message:"Error in calculating matching percentage of X path content and bound content",error:t.toString()}})}}getHighlightRange(t,e,n,r,o){const i=this.getNodeFromXPath(t),s=this.getNodeFromXPath(e);if(!i)throw new Error("Node not found for startNodeXpath: "+t);if(!s)throw new Error("Node not found for endNodeXPath: "+e);if(i.nodeType!==Node.TEXT_NODE)throw new Error("Start node is not a text node: "+t);if(s.nodeType!==Node.TEXT_NODE)throw new Error("End node is not a text node: "+e);const a=document.createRange();if(a.setStart(i,n),a.setEnd(s,r),this.logAttributionSuccessPercentage(a.toString(),o),this.isRangeVisible(a))return a;throw new Error(`Range is not visible. startNodeXpath: ${t}, endNodeXPath: ${e}`)}removeHighlights(){util.consoleLog("Removing highlights"),this.highlight.clear()}rangeHighlightHandler(t){this.highlight.add(t),CSS.highlights.set("search-results",this.highlight),t?.startContainer?.parentElement.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"});const e=t.getBoundingClientRect(),n=e.top+window.scrollY+e.height/2-window.innerHeight/2;window.scrollTo({top:n,behavior:"smooth"})}canHighlightText(t){util.consoleLog("Checking if text can be highlighted: ",t);const{source:{bounds:e}}=t;let n=!1;for(const t of e){const{text:e,start_offset:r,end_offset:o,start_xpath:i,end_xpath:s,startOffsetInOriginal:a,endOffsetInOriginal:h}=t;try{this.getHighlightRange(i,s,a||r,h||o,e)&&(n=!0)}catch(t){chrome.runtime.sendMessage({main_op:"log-error",log:{message:"Error in checking if text can be highlighted",error:t.toString(),url:window.location.href,text:e}})}}return n}sanitiseSources(t){const{sources:e=[]}=t;return e.filter(t=>({sourceRes:this.canHighlightText({source:t})}))}highlightText(t){this.removeHighlights(),util.consoleLog("Highlighting text: ",t);const{source:{bounds:e}}=t;let n=!1;for(const t of e){const{text:e,start_offset:r,end_offset:o,start_xpath:i,end_xpath:s,startOffsetInOriginal:a,endOffsetInOriginal:h}=t;try{const t=this.getHighlightRange(i,s,a||r,h||o,e);this.rangeHighlightHandler(t),n=!0}catch(t){chrome.runtime.sendMessage({main_op:"log-error",log:{message:"Error in Highlighting Attribution",error:t.toString(),url:window.location.href,text:e}})}e||chrome.runtime.sendMessage({main_op:"log-error",log:{message:"Error in Highlighting Attribution",start_xpath:i,end_xpath:s,startOffsetInOriginal:a,endOffsetInOriginal:h,error:"Attribution Text is empty"}})}return n?ATTRIBUTION_HIGHLIGHTING_STATUS.SUCCESS:ATTRIBUTION_HIGHLIGHTING_STATUS.ERROR}}