Files
TinderPokemon/index.html

284 lines
13 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<!-- Bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.5/dist/umd/popper.min.js"
integrity="sha384-Xe+8cL9oJa6tN/veChSP7q+mnSPaj5Bcu9mPX5F5xIGE0DVittaqT5lorf0EI7Vk"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.min.js"
integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK"
crossorigin="anonymous"></script>
<title>Tinder Pokemon</title>
<link rel="icon" type="image/x-icon" href="assets/img/Icon.ico">
<link rel="manifest" href="assets/JsStuff/manifest.webmanifest">
</head>
<script>
if ('serviceWorker' in navigator) {
// Register a service worker hosted at the root of the
// site using the default scope.
navigator.serviceWorker.register('/PokemonTinder/sw.js').then(
(registration) => {
console.log('Service worker registration succeeded:', registration)
},
/*catch*/(error) => {
console.log('Service worker registration failed:', error)
}
)
} else {
console.log('Service workers are not supported.')
}
</script>
<body id="main">
<div class="d-grid gap-2 text-center">
<div class="">
<h1>Tinder for weird furries</h1>
</div>
<div class="">
<h2>Home</h2>
</div>
</div>
<div class="container">
<div class="card p-2">
<img id="pokemonImage" style="image-rendering: pixelated;"
src="https://www.pokewiki.de/images/thumb/d/dd/Sugimori_132.png/250px-Sugimori_132.png"
class="card-img-top" style="" alt="...">
<div class="card-body">
<h4 class="card-title" id="pokemonName">Ditto</h4>
<h5 class="card-title" id="pokemonAge">21</h5>
<h5 class="card-title" id="pokemonDistance">35km Away</h5>
<p class="card-text" id="pokemonDescription">I like Ice Cream</p>
<div class="row">
<div class="btn col-4" id="nopeButton">
<div class="text-center">
<img src="assets/img/cross.png" class="rounded col-6" alt="Home">
</div>
</div>
<div class="btn col-4" id="favoriteButton">
<div class="text-center">
<img src="assets/img/star.png" class="rounded col-6" alt="Home">
</div>
</div>
<div class="btn col-4" id="likeButton">
<div class="text-center">
<img src="assets/img/105220.png" class="rounded col-6" alt="Home">
</div>
</div>
</div>
</div>
</div>
<div class="row fixed-bottom">
<div class="btn col-4 btn-light">
<a href="likes.html" style="text-decoration:none;color:black">
<h3>Liked</h3>
</a>
</div>
<div class="btn col-4 btn-light">
<a href="index.html" style="text-decoration:none;color:black">
<h3>Home</h3>
</a>
</div>
<div class="btn col-4 btn-light">
<a href="favorites.html" style="text-decoration:none;color:black">
<h3>Favorites</h3>
</a>
</div>
</div>
</div>
<i class="fa-solid fa-house"></i>
</body>
<script>
"use strict";
var CurrentPokemon = new Object();
var LoadedSuccessfully = false;
document.getElementById('main').onload = function () {
loadNewPokemon();
}
function loadNewPokemon() {
//We will need to load an image from the pokeAPI with his description and a random name/age
fetch("https://pokeapi.co/api/v2/pokemon/" + Math.floor(Math.random() * 905))
.then((response) => {
response.json()
.then((pokemonData) => {
fetch("https://tomatebanane.ch/api/pokename/random")
.then((response) => {
response.json()
.then((randomName) => {
fetch("https://pokeapi.co/api/v2/pokemon-species/" + pokemonData.id)
.then((response) => {
response.json()
.then((pokemonInfo) => {
console.log(pokemonData.id);
LoadedSuccessfully = true;
var age = (Math.floor(Math.random() * (65 - 18)) + 18);
CurrentPokemon.name = randomName[0].name;
CurrentPokemon.id = uniqid();
CurrentPokemon.pokemonId = pokemonData.id;
CurrentPokemon.pp = pokemonData.sprites.front_shiny;
CurrentPokemon.age = age;
CurrentPokemon.description = pokemonInfo.flavor_text_entries[0].flavor_text;
document.getElementById("pokemonName").innerHTML = randomName[0].name;
document.getElementById("pokemonImage").src = pokemonData.sprites.front_shiny;
document.getElementById("pokemonAge").innerHTML = age;
document.getElementById("pokemonDescription").innerHTML = pokemonInfo.flavor_text_entries[0].flavor_text;
window.navigator.geolocation.getCurrentPosition(function (pos) {
var lat = pos.coords.latitude;
var lon = pos.coords.longitude;
let pokemonLatitude = Math.floor(Math.random() * 180) - 90;
let pokemonLongitude = Math.floor(Math.random() * 360) - 180;
let dist = distance(lon, lat, pokemonLongitude, pokemonLatitude);
document.getElementById("pokemonDistance").innerHTML = Math.floor(dist) + " Km away";
})
})
}).catch((response) => {
alert("Bouhouuuuu could not get any further infos on that dumbass");
})
})
.catch((response => {
alert("Bouhouuu i cant convert a response into json");
}))
}).catch((response) => {
alert("Could not get the magnificien datas from Zanardi's API");
})
})
.catch(data => {
alert("Bouhouuuu I cant convert a response to json");
});
})
.catch(response => {
alert("This could use a error handler but for now lets just say that there was an problem trying to get the infos from pokeAPI");
})
}
document.getElementById('likeButton').onclick = function () {
if (LoadedSuccessfully) {
//saveToIndexedDB("likes", CurrentPokemon);
storeToApi("likes", CurrentPokemon);
loadNewPokemon();
}
};
document.getElementById('nopeButton').onclick = function () {
if (LoadedSuccessfully) {
saveToIndexedDB("nopes", CurrentPokemon);
loadNewPokemon();
}
}
document.getElementById('favoriteButton').onclick = function () {
if (LoadedSuccessfully) {
//saveToIndexedDB("favorites", CurrentPokemon);
storeToApi("favorites", CurrentPokemon);
loadNewPokemon();
}
}
// !! THIS METHOD IS NOT MINE, ITS FROM STACK OVERFLOW : https://stackoverflow.com/questions/13840516/how-to-find-my-distance-to-a-known-location-in-javascript
function distance(lon1, lat1, lon2, lat2) {
var R = 6371; // Radius of the earth in km
var dLat = (lat2 - lat1).toRad(); // Javascript functions in radians
var dLon = (lon2 - lon1).toRad();
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c; // Distance in km
return d;
}
/** Converts numeric degrees to radians */
if (typeof (Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
}
window.navigator.geolocation.getCurrentPosition(function (pos) {
//console.log(pos);
//console.log(
//distance(pos.coords.longitude, pos.coords.latitude, 42.37, 71.03)
//);
});
// THIS FUNCTION IS ALSO NOT MINE AND ITS FROM STACK OVERFLOW TOO : https://stackoverflow.com/questions/4872380/uniqid-in-javascript-jquery
function uniqid(prefix = "", random = false) {
const sec = Date.now() * 1000 + Math.random() * 1000;
const id = sec.toString(16).replace(/\./g, "").padEnd(14, "0");
return `${prefix}${id}${random ? `.${Math.trunc(Math.random() * 100000000)}` : ""}`;
};
//Wow again, not my function almost seems like I did nothing in that code
function saveToIndexedDB(storeName, object) {
return new Promise(
function (resolve, reject) {
if (object.id === undefined) reject(Error('object has no id.'));
var dbRequest = indexedDB.open(storeName);
dbRequest.onerror = function (event) {
reject(Error("IndexedDB database error"));
};
dbRequest.onupgradeneeded = function (event) {
var database = event.target.result;
var objectStore = database.createObjectStore(storeName, { keyPath: "id" });
};
dbRequest.onsuccess = function (event) {
var database = event.target.result;
var transaction = database.transaction([storeName], 'readwrite');
var objectStore = transaction.objectStore(storeName);
var objectRequest = objectStore.put(object); // Overwrite if exists
objectRequest.onerror = function (event) {
reject(Error('Error text'));
};
objectRequest.onsuccess = function (event) {
resolve('Data saved OK');
console.log("Data saved successfully");
};
};
}
);
}
//This code... you wont believe it... its still not mine HAHAHAHAHA but now its from postman
function storeToApi(storeName, pokemon) {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("name", pokemon.name);
urlencoded.append("pokemonId", pokemon.pokemonId);
urlencoded.append("pp", pokemon.pp);
urlencoded.append("age", pokemon.age);
urlencoded.append("description", pokemon.description);
urlencoded.append("indexDbId", pokemon.id);
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("https://633bde0df11701a65f69abe8.mockapi.io/api/v1/" + storeName + "/", requestOptions)
.then(response => response.text())
.then(result => {
let addedPokemon = JSON.parse(result);
console.log(addedPokemon);
saveToIndexedDB(storeName, addedPokemon);
})
.catch(error => console.log('error', error));
}
</script>
</html>