import { Controller } from "@hotwired/stimulus"; export default class extends Controller { static values = { logoType: String, employerName: String } static targets = ["preview", "previewContainer", "logoSelect", "logoField", "initialLogoFile"]; async connect() { console.log('in connect'); const initValue = this.logoFieldTarget.value console.log(initValue) if (initValue) { const response = await fetch(`/id_card/${this.logoTypeValue}_logos/${initValue}/image`); // Fetch the binary data const blob = await response.blob(); const objectUrl = URL.createObjectURL(blob); this.previewTarget.src = objectUrl; this.previewContainerTarget.classList.remove("hidden"); } // Remember to revoke the URL when the controller is disconnected if necessary // this.disconnect = () => URL.revokeObjectURL(objectUrl); } uploadLogo(event) { console.log('in uploadLogo'); event.preventDefault() let logoFile = event.target.files[0]; if (!logoFile) return; const logoType = this.logoTypeValue let newFileName = logoFile.name if (logoType == "network") { console.log("n " + newFileName); newFileName = this.determineNetworkFilename(logoFile) this.addOptionToSelect(newFileName) logoFile = new File([logoFile], newFileName) } else if (logoType == "employer") { newFileName = this.determineEmployerFilename(logoFile) logoFile = new File([logoFile], newFileName) } this.uploadLogoToServer(logoFile) .then((result) => { console.log(result); const logoId = result.id this.previewFile(logoFile); this.logoFieldTarget.value = logoId; }) .catch((error) => { // Handle any errors that occurred console.error(error); }); } previewFile(logoFile) { console.log('in previewFile'); const reader = new FileReader(); reader.onload = (e) => { this.previewTarget.src = e.target.result; this.previewContainerTarget.classList.remove("hidden"); }; reader.readAsDataURL(logoFile); } async uploadLogoToServer(logoFile) { console.log('in uploadLogoToServer'); const formData = new FormData(); formData.append(`id_card_${this.logoTypeValue}_logo[logo_file]`, logoFile); const csrfToken = document.querySelector("meta[name='csrf-token']").content; try { const response = await fetch(`/id_card/${this.logoTypeValue}_logos/`, { method: "POST", headers: { "X-CSRF-Token": csrfToken }, body: formData }); if (response.ok) { console.log('Upload successful!') const data = await response.json(); return data; } else { throw new Error(`HTTP error! status: ${response.status}`); } } catch (error) { console.error("Network error:", error); throw new Error("Network error:", error); } } addOptionToSelect(name) { const blankOptionIndex = 0; const newOption = new Option(name, name, true, true) if (this.logoFieldTarget.options.length > blankOptionIndex + 1) { this.logoFieldTarget.insertBefore(newOption, this.logoFieldTarget.options[blankOptionIndex + 1]); } else { this.logoFieldTarget.appendChild(newOption); } this.logoFieldTarget.value = name; } determineNetworkFilename(logoFile) { const fileExtension = logoFile.name.split('.').pop(); const primaryNetworkName = prompt("Enter the name for the primary network (Usually 'Cigna' or 'MedCost':"); const secondaryNetworkName = prompt("Enter the name for the primary network (ex: Health Partners):"); const logoFilename = this.titleizeText(primaryNetworkName).concat(this.titleizeText(secondaryNetworkName)).concat("Logo.").concat(fileExtension).replaceAll(' ', ''); return logoFilename } determineEmployerFilename(logoFile) { const fileExtension = logoFile.name.split('.').pop(); const employerName = this.employerNameValue const logoFilename = this.titleizeText(employerName).concat("Logo.").concat(fileExtension).replaceAll(' ', ''); return logoFilename } titleizeText(text) { const titleized = text.toLowerCase(); return titleized.replace(/(^|\s)\S/g, function(match) { return match.toUpperCase(); }); } }