/*************************************************************************
* 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{createURLForAttachment,updateDrivePDFUrl}from"./util.js";import{getElementListForSelectors,buildAcrobatPromotionSource,createAcrobatIconElement,getElementsListBasedOnSelectors,getFirstElementBasedOnSelectors,getClosestElementBySelectors,getElementFromParent,sendAnalytics,sendErrorLog}from"../utils/util.js";import state from"./state.js";import{acrobatTouchPointClicked}from"../utils/fte-utils.js";import{shouldShowFTE,isEnoughSpaceToShowFTE,alignFTETooltipToButton,updateAttachmentContainerTitle}from"./gmail-compress-pdf-fte-service.js";const GMAIL_COMPRESS_TOUCH_POINT_ICON_CLASS="gmail-compress-pdf-touch-point-icon",GMAIL_COMPRESS_TOUCH_POINT_TEXT_CLASS="gmail-compress-pdf-touch-point-text",GMAIL_COMPRESS_TOUCH_POINT_CLASS="gmail-compress-pdf-touch-point",GMAIL_COMPRESS_TOUCH_POINT_DRIVE_CLASS="gmail-compress-pdf-drive-touch-point",GMAIL_COMPRESS_PDF_FTE_TOOLTIP_STORAGE_KEY="acrobat-gmail-compress-pdf-fte-config",GMAIL_DRIVE_ATTACHMENT_HOSTNAME="drive.google.com",GMAIL_FILES_ATTACHMENT_HOSTNAME="mail.google.com",ACROBAT_ATTACHMENT_PROCESSED_ATTRIBUTE="acrobat-compose-box-attachment-processed",ACROBAT_COMPOSE_BOX_PROCESSED_ATTRIBUTE="acrobat-compose-box-processed",ACROBAT_PROCESSED_VALUE="Y",SOURCE="gmail_chrome",createCompressPDFTextElement=()=>{const e=document.createElement("span");return e.setAttribute("class","gmail-compress-pdf-touch-point-text"),e.textContent=state?.gmailCompressPDFConfig?.compressPDFString,e},createCompressPDFTouchPoint=e=>{const t=document.createElement("div"),o=createAcrobatIconElement("gmail-compress-pdf-touch-point-icon","browser/images/acrobat_dc_appicon_128.png"),s=createCompressPDFTextElement();return t.appendChild(o),t.appendChild(s),t.setAttribute("class","gmail-compress-pdf-touch-point"),"drive"===e&&t.classList.add("gmail-compress-pdf-drive-touch-point"),t},handleCompressPDFTouchPointClick=(e,t)=>{try{acrobatTouchPointClicked("acrobat-gmail-compress-pdf-fte-config"),window.open(e,"_blank"),sendAnalytics([["DCBrowserExt:DirectVerb:CTA:Clicked",{source:SOURCE,workflow:t}]]),chrome.runtime.sendMessage({main_op:"akamai-ping"})}catch(e){sendErrorLog("GmailCompressPDFTouchPoint","Failure in opening pdf on compress PDF touch point click")}},getCompressPDFTouchPointUrl=(e,t,o)=>{if(!e)return null;const s=buildAcrobatPromotionSource(SOURCE,"file"===o?"compress_pdf_file":"compress_pdf_drive");let n=e.toString();return n&&"drive"===o&&(n=updateDrivePDFUrl(n)),createURLForAttachment(n,s,t,"compresspdf")},getPDFAttachmentSize=e=>{const t=e.match(/\(([^()]*)\)\s*$/);if(!t)return null;return t[1].replace(/\D/g,"")},addTouchPointToMessageWithPDFAttachment=(e,t,o=!1)=>{try{const s=createCompressPDFTouchPoint(t);e.appendChild(s);const n=s.getBoundingClientRect().width;return updateAttachmentContainerTitle(e,t,n),e.setAttribute(ACROBAT_ATTACHMENT_PROCESSED_ATTRIBUTE,"Y"),state&&state.compressPdfFteState&&!1===o&&(state.compressPdfFteState.compressPDFTouchPointWithFTE=s),chrome.runtime.sendMessage({main_op:"reRenderShowOneChild"}),s}catch(e){return sendErrorLog("GmailCompressPDFTouchPoint","Failure in adding compress PDF touch point to message with PDF attachment"),null}},isValidPDFDocumentUrl=({message:e,url:t,name:o})=>{if("drive.google.com"===t.hostname){if(getFirstElementBasedOnSelectors(state?.gmailCompressPDFConfig?.selectors?.pdfAttachmentIcon,e))return!0;return!(!getFirstElementBasedOnSelectors(state?.gmailCompressPDFConfig?.selectors?.genericAttachmentIcon,e)||!o.toLowerCase().endsWith(".pdf"))}return!("mail.google.com"!==t.hostname||!o.toLowerCase().endsWith(".pdf"))},getSanitizedPDFAttachmentName=e=>{if(!e)return"";const t=e.toLowerCase(),o=t.lastIndexOf(".pdf");if(-1!==o)return e.substring(0,o+4).trim();const s=t.lastIndexOf("(");return-1!==s?t.substring(0,s).trim():e.trim()},getValidPDFAttachmentUrl=e=>{try{return new URL(e.href)}catch{return sendErrorLog("GmailCompressPDFTouchPoint","Failed to get attachment URL - invalid href"),null}},meetsSizeThresholdForCompression=(e,t)=>{if("file"===t&&null!==e)try{const t=Number(e);if(Number.isNaN(t)||t<state?.gmailCompressPDFConfig?.compressPDFSizeThreshold)return!1}catch(e){return sendErrorLog("GmailCompressPDFTouchPoint","Failed to convert PDF attachment size to number"),!1}return!0},getAllUnprocessedMessagesWithPDFAttachment=(e,t)=>{const o=state?.gmailCompressPDFConfig?.selectors?.[t]?.attachmentContainer,s=o.map(e=>`${e}:not([${ACROBAT_ATTACHMENT_PROCESSED_ATTRIBUTE}="Y"])`),n=getElementsListBasedOnSelectors(s,e);return Array.isArray(n)&&0!==n.length?n.map(e=>{const o=state?.gmailCompressPDFConfig?.selectors?.[t]?.pdfAttachmentElement,s=getFirstElementBasedOnSelectors(o,e);if(!s)return null;const n=getValidPDFAttachmentUrl(s);if(!n)return null;const r=getSanitizedPDFAttachmentName(s.innerText),i=getPDFAttachmentSize(s.innerText);return meetsSizeThresholdForCompression(i,t)?{message:e,url:n,name:r}:null}).filter(e=>e&&isValidPDFDocumentUrl({...e})):null},addTouchPointInComposeBoxPDFAttachment=async(e,t)=>{const o=getAllUnprocessedMessagesWithPDFAttachment(e,t);if(!Array.isArray(o))return;const s=o.map(async e=>{if(getElementFromParent(["gmail-compress-pdf-touch-point"],e.message))return;const o=await isEnoughSpaceToShowFTE(t,e.message),s=null===state?.compressPdfFteState.compressPDFTouchPointWithFTE;o&&s&&addTouchPointToMessageWithPDFAttachment(e.message,t)});await Promise.all(s)},getCompressPDFClickEventDetails=e=>{let t=e.target;if(t&&!t.classList.contains("gmail-compress-pdf-touch-point")&&(t=t.parentElement,t&&!t.classList.contains("gmail-compress-pdf-touch-point")))return null;const o=t.parentElement;if(!o)return null;const s=getFirstElementBasedOnSelectors(["a"],o);if(!s)return null;const n=t.classList.contains("gmail-compress-pdf-drive-touch-point")?"drive":"file";let r,i;return"file"===n?(r=state?.gmailCompressPDFConfig?.selectors?.[n]?.pdfAttachmentTitle.map(e=>`.${e}`),i="compress_pdf_file"):(r=state?.gmailCompressPDFConfig?.selectors?.[n]?.pdfAttachmentTitle,i="compress_pdf_drive"),{closestAnchorElement:s,pdfAttachmentLocation:n,pdfAttachmentNameSelector:r,workflow:i}},handleComposeBoxClickEvent=e=>{const t=getCompressPDFClickEventDetails(e);if(!t)return;const{closestAnchorElement:o,pdfAttachmentLocation:s,pdfAttachmentNameSelector:n,workflow:r}=t,i=getFirstElementBasedOnSelectors(n,o);if(!i)return;const a=getSanitizedPDFAttachmentName(i.innerText),c=getValidPDFAttachmentUrl(o);if(!c)return;const m=getCompressPDFTouchPointUrl(c,a,s);m&&handleCompressPDFTouchPointClick(m,r)},removeOtherCompressPDFTouchPoints=()=>{const e=getElementListForSelectors(["gmail-compress-pdf-touch-point"],document);Array.isArray(e)&&e.forEach(e=>{e!==state?.compressPdfFteState?.compressPDFTouchPointWithFTE&&e.remove()})},checkPDFAttachmentInUploadedState=(e,t)=>{const o=state?.gmailCompressPDFConfig?.selectors?.[t]?.pdfAttachmentElement,s=getFirstElementBasedOnSelectors(o,e);return s?.href?s:null},adjustExistingFTETouchpointPosition=(e,t,o)=>{const s="drive"===t,n=state?.compressPdfFteState?.compressPDFTouchPointWithFTE;s&&!o&&n===e&&(e.style.right="0%")},isValidPDFAttachmentForCompression=(e,t)=>{const o=checkPDFAttachmentInUploadedState(e,t);if(!o)return!1;const s=getSanitizedPDFAttachmentName(o.innerText),n=getPDFAttachmentSize(o.innerText);if(!meetsSizeThresholdForCompression(n,t))return!1;const r=getValidPDFAttachmentUrl(o);if(!r)return!1;return!!isValidPDFDocumentUrl({message:e,url:r,name:s})},setCompressPDFTouchPointPosition=(e,t,o)=>{e.style.right="drive"===t&&o?"7.75%":"0%"},handleComposeBoxMouseOverEvent=(e,t,o,s)=>{const n=getElementFromParent(["gmail-compress-pdf-touch-point"],e);if(n)return void adjustExistingFTETouchpointPosition(n,t,s);if(removeOtherCompressPDFTouchPoints(),!isValidPDFAttachmentForCompression(e,t))return;const r=addTouchPointToMessageWithPDFAttachment(e,t,!0);r&&(setCompressPDFTouchPointPosition(r,t,s),sendAnalytics([["DCBrowserExt:DirectVerb:CTA:Shown",{source:SOURCE,workflow:o}]]))},handleComposeBoxMouseOutEvent=(e,t,o,s)=>{if(getClosestElementBySelectors(e.relatedTarget,state?.gmailCompressPDFConfig?.selectors?.drive?.attachmentContainer))return;if(getClosestElementBySelectors(e.relatedTarget,state?.gmailCompressPDFConfig?.selectors?.file?.attachmentContainer))return;const n=getElementFromParent(["gmail-compress-pdf-touch-point"],t);if(!n)return;"drive"===o&&!s&&state?.compressPdfFteState?.compressPDFTouchPointWithFTE===n&&(n.style.right="7.75%"),state?.compressPdfFteState?.compressPDFTouchPointWithFTE!==n&&(n.remove(),updateAttachmentContainerTitle(t,o))},getAttachmentContainerInfo=e=>{let t=getClosestElementBySelectors(e,state?.gmailCompressPDFConfig?.selectors?.drive?.attachmentContainer);return t?{closestAttachmentContainer:t,attachmentLocation:"drive",workflow:"compress_pdf_drive"}:(t=getClosestElementBySelectors(e,state?.gmailCompressPDFConfig?.selectors?.file?.attachmentContainer),t?{closestAttachmentContainer:t,attachmentLocation:"file",workflow:"compress_pdf_file"}:null)},handleComposeBoxMouseEvent=(e,t)=>{const o=getAttachmentContainerInfo(e.target);if(!o)return;const{closestAttachmentContainer:s,attachmentLocation:n,workflow:r}=o,i=getFirstElementBasedOnSelectors(state?.gmailCompressPDFConfig?.selectors?.forwardComposeBox,t);"mouseover"===e.type?handleComposeBoxMouseOverEvent(s,n,r,i):"mouseout"===e.type&&handleComposeBoxMouseOutEvent(e,s,n,i)},addListenerToComposeBox=e=>{"Y"===e.getAttribute("acrobat-compose-box-processed")||(e.addEventListener("click",handleComposeBoxClickEvent),["mouseover","mouseout"].forEach(t=>{e.addEventListener(t,t=>{handleComposeBoxMouseEvent(t,e)})}),e.setAttribute("acrobat-compose-box-processed","Y"))},getAllComposeBoxes=()=>getElementListForSelectors(state?.gmailCompressPDFConfig?.selectors?.composeBox,document),addTouchPointToComposeBoxPDFAttachment=async()=>{state?.compressPdfFteState.compressPDFTouchPointWithFTE&&alignFTETooltipToButton();const e=getAllComposeBoxes();if(!Array.isArray(e))return;const t=e.map(async e=>{addListenerToComposeBox(e);await shouldShowFTE()&&(await addTouchPointInComposeBoxPDFAttachment(e,"file"),await addTouchPointInComposeBoxPDFAttachment(e,"drive"))});await Promise.all(t)};export{addTouchPointToComposeBoxPDFAttachment};