/*************************************************************************
* 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 state from"./state.js";import{getClosestElementBasedOnSelector,getElementBasedOnSelector,getArrayElementBasedOnSelector,isOrphanContentScript,createURLForAttachment,LIST_VIEW,isDriveFileDirectDownloadLink}from"./util.js";import{isDefaultViewer,openPdfInNewTab}from"./default-viewership-service.js";import{buildAcrobatPromotionSource,sendAnalytics,sendAnalyticsOncePerMonth,createAcrobatIconElement}from"../utils/util.js";import{createFteTooltip,shouldShowFteTooltip,updateFteToolTipCoolDown,acrobatTouchPointClicked,getAcrobatTouchPointFteEligibility,removeFteTooltip as removeFteTooltipUtil}from"../utils/fte-utils.js";import{sendAnalyticsIfNativeViewerLaunched,processForNativeViewer}from"./native-viewer-touch-point-service.js";const ACROBAT_PROCESSED_ATTRIBUTE="acrobat-icon-added",LIST_VIEW_TOUCH_POINT_CLASS="acrobat-attachmentlistview-hyperlink",LIST_VIEW_TOUCH_POINT_VISIBLE="acrobat-gmail-attachment-visible",GMAIL_FTE_TOOLTIP_STORAGE_KEY="acrobat-gmail-fte-config",GMAIL_FTE_TOOLTIP_CONTAINER_CLASS="acrobat-fte-tooltip-container",revertAttachmentParentDivStyle=e=>{e?.style?.removeProperty("padding-right")},createAcrobatTooltip=()=>{const e=document.createElement("div");return e.setAttribute("class","acrobat-attachmentlistview-hyperlink-tooltip"),e.innerText=state?.gmailConfig?.acrobatPromptText,e},handleAcrobatHyperLinkClickForFte=()=>{const e=document.getElementsByClassName("acrobat-fte-tooltip-container");e?.length>0&&(state.fteToolTip.eligibleFte.type="",state.fteToolTip.touchPointClicked=!0,removeFteTooltipFromAttachmentDiv(),sendAnalytics(["DCBrowserExt:GmailFTE:ListView:Dismissed"])),document.removeEventListener("click",handleFteClickOutside),acrobatTouchPointClicked("acrobat-gmail-fte-config")};function resetTitleFromOldTitle(e){const t=e?.getAttribute("oldTitle");t&&(e?.setAttribute("title",t),e?.setAttribute("oldTitle",""))}const createAcrobatHyperlinkForListViewAttachment=(e,t)=>{const i=e.url,o=e.name,n=document.createElement("a");n.setAttribute("class",LIST_VIEW_TOUCH_POINT_CLASS);const a=buildAcrobatPromotionSource("gmail_chrome","list"),r=createURLForAttachment(i,a,o);n.setAttribute("href",r),n.setAttribute("target","_blank");let s=createAcrobatIconElement("acrobat-icon",state?.iconURLListView||"browser/images/acrobat_dc_trefoil_24_white.svg");return n.appendChild(s),n.addEventListener("click",i=>{i.stopPropagation(),resetTitleFromOldTitle(t);sendAnalytics([[e?.isDriveAsset?"DCBrowserExt:Gmail:ListViewPrompt_DriveLink:Clicked":"DCBrowserExt:Gmail:ListViewPrompt:Clicked",{gsuiteFte:getAcrobatTouchPointFteEligibility()}]]),handleAcrobatHyperLinkClickForFte(),chrome.runtime.sendMessage({main_op:"akamai-ping"})}),n.addEventListener("mouseenter",e=>{t?.setAttribute("oldTitle",t?.getAttribute("title")),e?.target?.parentElement?.setAttribute("title","")}),n.addEventListener("mouseleave",()=>{resetTitleFromOldTitle(t)}),n},getListViewPDFAttachmentsWithoutAcrobatIcon=(e,t)=>{if(!getElementBasedOnSelector(e,"pdfAttachmentWithoutAcrobatIcon","listView"))return;const i=getArrayElementBasedOnSelector(e,"pdfAttachmentWithoutAcrobatIcon","listView");let o={};if(i&&i.length>0)for(let e=0;e<i.length;e++){const n=getClosestElementBasedOnSelector(i[e],"threadElement","listView"),a=n.querySelector("[data-thread-id]");if(!a)return;const r=a.getAttribute("data-thread-id"),s=r?.substring(r?.indexOf("#")+1);isDataPresentForThreadId(s,t)&&(o[s]?o[s].pdfAttachments.push(i[e]):(o[s]={},o[s].pdfAttachments=[i[e]],o[s].threadElement=n))}return o},getSortedMessageIds=e=>{let t=Object.keys(e).sort((t,i)=>-e[t].timestamp+e[i].timestamp);const i=t.filter(t=>e[t]?.deleted);return t=t.filter(t=>!e[t]?.deleted),t.push(...i),t},getAttachmentURLAgainstName=(e,t)=>{const i={};for(let o=0;o<e.length;o++){const n=t[e[o]];if(n.attachments?.length>0)for(let e=0;e<n.attachments.length;e++){const t=n.attachments[e];i[t.name]?i[t.name].push(t):i[t.name]=[t]}if(n.driveAttachments?.length>0)for(let e=0;e<n.driveAttachments.length;e++){const t=n.driveAttachments[e];i[t.name]?i[t.name].push(t):i[t.name]=[t]}}return i},isDataPresentForThreadId=(e,t)=>{let i=state.getMessagesForThreadId(e);return!i&&t&&t[e]&&(i=t[e].messages),!!i},getDataForThreadId=(e,t)=>{let i=state.getMessagesForThreadId(e);if(!i&&t&&t[e]&&(i=t[e].messages),i){let e=getSortedMessageIds(i);return getAttachmentURLAgainstName(e,i)}return null},isMultipleAttachmentWithSameName=(e,t)=>{const i=e[t];return i?.length>1},getAttachmentDetailsFromThreadData=(e,t,i)=>{const o=e[t];if(!o)return null;for(let e=0;e<o?.length;e++)if(!i.includes(o[e].url))return i.push(o[e].url),o[e]},makeTouchPointVisibleWhenAttachmentIsHovered=(e,t,i)=>{e.addEventListener("mouseenter",()=>{isLargeLayout(i)&&!isOrphanContentScript()&&(t.style.display="flex",e.style.paddingRight="0")},{signal:state.eventControllerSignal})},hideTouchPointWhenUserLeavesTheThread=(e,t,i)=>{i?.addEventListener("mouseleave",()=>{isLargeLayout(e)&&t&&(t.style.display="none",t.classList.contains(LIST_VIEW_TOUCH_POINT_VISIBLE)||i.style.removeProperty("padding-right"))},{signal:state.eventControllerSignal})},removeTouchPointFromAttachmentDiv=e=>{const t=e?.getElementsByClassName(LIST_VIEW_TOUCH_POINT_CLASS);t?.length>0&&e.removeChild(t[0])},removeFteTooltipFromAttachmentDiv=()=>{const e=document.getElementsByClassName(LIST_VIEW_TOUCH_POINT_VISIBLE);if(e&&e[0]){const t=getClosestElementBasedOnSelector(e[0],"threadElement","listView");t&&t?.style?.removeProperty("z-index"),e[0].style.display="none",e[0].appendChild(createAcrobatTooltip()),e[0].parentElement.style.removeProperty("padding-right"),e[0].setAttribute("class",LIST_VIEW_TOUCH_POINT_CLASS)}removeFteToolTip()},removeFteToolTip=()=>{removeFteTooltipUtil(),state.fteToolTip.eligibleFte={type:""}},handleFteClickOutside=(e,t)=>{document.getElementsByClassName("acrobat-fte-tooltip-container").length>0&&"listView"===state?.fteToolTip?.eligibleFte?.type&&(t.contains(e.target)||(sendAnalytics(["DCBrowserExt:GmailFTE:ListView:Dismissed"]),document.removeEventListener("click",handleFteClickOutside))),removeFteTooltipFromAttachmentDiv()},addFteTooltipButtonEventListener=(e,t,i,o)=>{o.querySelector(".acrobat-fte-tooltip-button").addEventListener("click",()=>{removeFteTooltipFromAttachmentDiv(),sendAnalytics(["DCBrowserExt:GmailFTE:ListView:Clicked"]),document.removeEventListener("click",handleFteClickOutside)})},handleAcrobatTouchPointClickForFte=()=>{removeFteTooltipFromAttachmentDiv(),document.removeEventListener("click",handleFteClickOutside)},addFteTooltipToAttachmentDiv=(e,t,i)=>{let o="listView";isLastThreadInMail(e)&&(o="listViewLastThread");const n=createFteTooltip(state?.gmailConfig?.gmailFteToolTipStrings,o);addFteTooltipButtonEventListener(0,0,0,n),i.style.zIndex="3",t.addEventListener("click",()=>handleAcrobatTouchPointClickForFte(),{once:!0}),document.addEventListener("click",e=>handleFteClickOutside(e,n),{once:!0,signal:state?.eventControllerSignal});const a=state?.gmailConfig?.fteConfig?.tooltip;""===state?.fteToolTip?.eligibleFte?.type&&(state.fteToolTip.eligibleFte={type:"listView",href:window.location.href},sendAnalytics(["DCBrowserExt:GmailFTE:ListView:Shown"]),updateFteToolTipCoolDown(a,"acrobat-gmail-fte-config").then(e=>{state.fteToolTip={...state?.fteToolTip,...e}})),t.appendChild(n)},isLastThreadInMail=e=>{const t=e.getBoundingClientRect();return window.innerHeight-t.bottom<130},isThreadVisibleInViewPort=e=>{const t=e.getBoundingClientRect();return t.top>=0&&t.bottom<=window.innerHeight},shouldShowListViewFte=(e,t)=>{if(!isThreadVisibleInViewPort(t))return!1;if(state?.isAcrobatDefaultForGmailPDFs)return!1;if(document.getElementsByClassName("acrobat-fte-tooltip-container").length>0)return!1;if(!isLargeLayout(t))return!1;const i=window.location.href,o=state?.fteToolTip?.eligibleFte;return"listView"===o?.type?o?.href===i:(""===o?.type||"listView"===o?.type)&&e},handleGmailFteTooltip=(e,t,i,o)=>{shouldShowListViewFte(e,o)?(gmailAcrobatFteCoachmark.setEligibility(!0,()=>{t.style.paddingRight="0",i.classList.add(LIST_VIEW_TOUCH_POINT_VISIBLE),addFteTooltipToAttachmentDiv(t,i,o)}),chrome.runtime.sendMessage({main_op:"reRenderShowOneChild"})):(e||gmailAcrobatFteCoachmark.setEligibility(!1),i.appendChild(createAcrobatTooltip()))},addFteWithoutCoolDown=()=>{const e=document.getElementsByClassName(LIST_VIEW_TOUCH_POINT_CLASS);if(e?.length>0){const t=getClosestElementBasedOnSelector(e[0],"attachmentDiv","listView");t.style.paddingRight="0",e[0].classList.add(LIST_VIEW_TOUCH_POINT_VISIBLE);const i=getClosestElementBasedOnSelector(e[0],"threadElement","listView");addFteTooltipToAttachmentDiv(t,e[0],i)}},addTouchPointToAttachmentDiv=async(e,t,i)=>{if(isDefaultViewer())return;const o=createAcrobatHyperlinkForListViewAttachment(t,e),n=state?.gmailConfig?.fteConfig?.tooltip;makeTouchPointVisibleWhenAttachmentIsHovered(e,o,i),hideTouchPointWhenUserLeavesTheThread(i,o,e),e.appendChild(o);const a=(await chrome.storage.local.get("gmailFteTab"))?.gmailFteTab;if(a?.value&&a?.expiry){if((new Date).getTime()<=a.expiry)return addFteWithoutCoolDown(),void chrome.storage.local.remove("gmailFteTab");chrome.storage.local.remove("gmailFteTab")}shouldShowFteTooltip(n,state?.fteToolTip,!0).then(t=>{handleGmailFteTooltip(t,e,o,i)})},handleAttachmentDivClickForFte=()=>{const e=document.getElementsByClassName("acrobat-fte-tooltip-container");e?.length>0&&(removeFteTooltipUtil(),sendAnalytics(["DCBrowserExt:GmailFTE:ListView:Dismissed"])),state.fteToolTip.eligibleFte.type="nativeView",document.removeEventListener("click",handleFteClickOutside)},handleClickAction=(e,t)=>{if("click"===e.type||"keydown"===e.type&&"Enter"===e.key){if(isDefaultViewer()&&t?.url){e.preventDefault(),e.stopPropagation();const i=buildAcrobatPromotionSource("gmail_chrome","list");openPdfInNewTab({url:t.url,touchPoint:i,attachmentName:t.name})}else handleAttachmentDivClickForFte(),setTimeout(()=>processForNativeViewer(t,LIST_VIEW),500),setTimeout(()=>processForNativeViewer(t,LIST_VIEW),1e3);sendAnalyticsOncePerMonth(`DCBrowserExt:Gmail:ListViewPDFAttachment${t?.isDriveAsset?"_DriveLink":""}:Clicked`)}},addClickListenerToAttachmentDiv=(e,t)=>{e.addEventListener("click",e=>handleClickAction(e,t),{signal:state?.eventControllerSignal,capture:!0}),e.addEventListener("keydown",e=>handleClickAction(e,t),{signal:state?.eventControllerSignal,capture:!0})},addClickListenerToDriveAttachmentDiv=(e,t)=>{e.addEventListener("click",()=>{sendAnalytics(["DCBrowserExt:Gmail:ListViewDrivePDFAttachment:Clicked"]),t&&!t?.isDriveAsset||setTimeout(()=>sendAnalyticsIfNativeViewerLaunched("DriveAttachment"),500)},{signal:state?.eventControllerSignal})},shouldShowTouchPoint=e=>e?.isDriveAsset?isDriveFileDirectDownloadLink(e.url):!!e,processForAttachment=(e,t,i,o)=>{const n=getClosestElementBasedOnSelector(e,"attachmentDiv","listView");if(n){removeTouchPointFromAttachmentDiv(n),e.setAttribute("acrobat-icon-added","Y");const a=n.getAttribute("title"),r=isMultipleAttachmentWithSameName(t,a);let s=getAttachmentDetailsFromThreadData(t,a,i);if(r&&!s.url?.includes("showSameMailAttachmentToast")&&(s={...s,url:s.url+"&showSameMailAttachmentToast=true"}),shouldShowTouchPoint(s)){const e=o.threadElement;addClickListenerToAttachmentDiv(n,s),addTouchPointToAttachmentDiv(n,s,e)}else addClickListenerToDriveAttachmentDiv(n,s)}},processForThread=(e,t,i)=>{const o=i.pdfAttachments,n=getDataForThreadId(e,t);if(!n)return;const a=[];for(let e of o)processForAttachment(e,n,a,i)},processForAllThreads=(e,t)=>{Object.keys(e).forEach(i=>{const o=e[i].pdfAttachments;if(o?.length>0){const o=e[i];processForThread(i,t,o)}})},removeAllTouchPoints=()=>{const e=document.querySelectorAll(`.${LIST_VIEW_TOUCH_POINT_CLASS}`);if(e?.length>0)for(let t=0;t<e.length;t++)revertAttachmentParentDivStyle(e[t]?.parentElement),e[t]?.parentElement?.removeChild(e[t]);removeFteToolTip()},addAcrobatTouchPointInTheListView=(e,t)=>{const i=getListViewPDFAttachmentsWithoutAcrobatIcon(e);i&&processForAllThreads(i,t)},isLargeLayout=e=>e?.getBoundingClientRect()?.width>900,getVisibleListView=()=>{const e=getArrayElementBasedOnSelector(document,"listView","listView");for(let t=0;t<e?.length;t++)if("none"!==e[t].style?.display)return e[t];return null},processForListView=e=>{try{if(chrome?.runtime?.id){const t=getVisibleListView();t&&addAcrobatTouchPointInTheListView(t,e)}}catch(e){}};export{processForListView,removeAllTouchPoints,isMultipleAttachmentWithSameName,getAttachmentDetailsFromThreadData,getVisibleListView,shouldShowTouchPoint,processForAttachment,processForThread,getSortedMessageIds};