mtgcsv/app.js
2024-08-20 22:27:26 -04:00

177 lines
6.0 KiB
JavaScript

import { randomWords } from './randomWords.js';
let cardList = [];
let soundThreshold = 1.00; // Default sound threshold
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('add-card-button').addEventListener('click', addCard);
document.getElementById('download-csv-button').addEventListener('click', downloadCSV);
document.getElementById('card-name').addEventListener('input', async function() {
const query = this.value;
const suggestions = await fetchCardSuggestions(query);
const suggestionsDiv = document.getElementById('suggestions');
suggestionsDiv.innerHTML = '';
suggestions.forEach(suggestion => {
const div = document.createElement('div');
div.textContent = suggestion;
div.onclick = () => {
document.getElementById('card-name').value = suggestion;
suggestionsDiv.innerHTML = '';
};
suggestionsDiv.appendChild(div);
});
});
// Update sound threshold based on user input
document.getElementById('sound-threshold').addEventListener('input', (event) => {
soundThreshold = parseFloat(event.target.value);
});
// Check and apply dark mode
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
if (isDarkMode) {
document.body.classList.add('dark-mode');
}
});
// Make toggleMenu globally accessible
window.toggleMenu = function toggleMenu() {
const menuContent = document.getElementById('menu-content');
menuContent.classList.toggle('show');
};
async function fetchCardSuggestions(query) {
const response = await fetch(`https://api.scryfall.com/cards/autocomplete?q=${encodeURIComponent(query)}`);
const data = await response.json();
return data.data;
}
async function fetchCardDetails(cardName, setCode) {
const response = await fetch(`https://api.scryfall.com/cards/named?exact=${encodeURIComponent(cardName)}&set=${encodeURIComponent(setCode)}`);
const data = await response.json();
return {
mana_cost: data.mana_cost || 'N/A',
power: data.power || 'N/A',
toughness: data.toughness || 'N/A',
type: data.type_line.split('—')[0].trim(), // Remove anything after em dash
rarity: data.rarity || 'N/A',
price: data.prices.usd || '0.00', // Fetching the price in USD
imageUrl: data.image_uris ? data.image_uris.small : null
};
}
async function addCard() {
const cardName = document.getElementById('card-name').value;
const setCode = document.getElementById('set-code').value;
const cardId = document.getElementById('card-id').value;
const quantity = document.getElementById('quantity').value;
const foil = document.getElementById('foil').value;
const cardDetails = await fetchCardDetails(cardName, setCode);
const cardData = {
name: cardName,
set: setCode,
card_id: cardId,
quantity: quantity,
foil: foil,
mana_type: cardDetails.mana_cost,
power: cardDetails.power,
toughness: cardDetails.toughness,
type: cardDetails.type,
rarity: cardDetails.rarity
};
cardList.push(cardData);
// Update the textarea with the new card information
let csvContent = generateCSVContent();
document.getElementById('csv-output').value = csvContent;
// Show the card image, name, and price in the dissolving popup
showCardPopup(cardName, cardDetails.imageUrl, cardDetails.price);
}
function generateCSVContent() {
let csvContent = "Card Name,Set,Card ID,Quantity,Foil,Mana Type,Power,Toughness,Type,Rarity\n";
cardList.forEach(card => {
const escapedValues = [
card.name,
card.set,
card.card_id,
card.quantity,
card.foil,
card.mana_type,
card.power,
card.toughness,
card.type,
card.rarity
].map(value => `"${value.replace(/"/g, '""')}"`); // Escape any existing quotes by doubling them
csvContent += escapedValues.join(",") + "\n";
});
return csvContent;
}
async function showCardPopup(cardName, imageUrl, price) {
const cardPopup = document.getElementById('card-popup');
cardPopup.innerHTML = `
<div style="font-family: 'Sorts Mill Goudy', serif; text-align: center;">
<strong>${cardName}</strong>
</div>
<img src="${imageUrl}" alt="${cardName}">
<div style="font-family: 'Sorts Mill Goudy', serif; text-align: center; margin-top: 10px;">
Price: $${price}
</div>
`;
cardPopup.style.display = 'block';
cardPopup.style.opacity = 1;
if (parseFloat(price) >= soundThreshold) {
playSound();
}
// Dissolve the popup after a few seconds
setTimeout(() => {
cardPopup.style.opacity = 0;
setTimeout(() => {
cardPopup.style.display = 'none';
}, 500);
}, 3000);
}
function playSound() {
const audio = new Audio('cash-money.mp3');
audio.play();
}
function getRandomWordsFromFile() {
let randomWordsSelected = [];
for (let i = 0; i < 3; i++) { // Get three random words
const randomIndex = Math.floor(Math.random() * randomWords.length);
randomWordsSelected.push(randomWords[randomIndex]);
}
return randomWordsSelected.join('-');
}
async function downloadCSV() {
const csvContent = generateCSVContent();
const randomFileName = getRandomWordsFromFile();
// Create a blob with the CSV content
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
// Create a temporary link element
const link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", `${randomFileName}.csv`);
document.body.appendChild(link);
// Trigger the download
link.click();
// Clean up and remove the link
document.body.removeChild(link);
}