-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMHWControllers.js
More file actions
368 lines (318 loc) · 9.81 KB
/
MHWControllers.js
File metadata and controls
368 lines (318 loc) · 9.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import * as MHW from "./MHWDatatypes.js";
/**
* DB connection controller
*/
class DataBase {
/**
* Searches for and returns a single equipment entry.
* @param {["head", "chest", "gloves", "waist", "legs"]} type Equipment type.
* @param {Number} id Equipment ID.
* @param {{}} projection {value: true, value: {value: true}}
* for all desired data.
* @returns {Promise<{}>} Equipment Item Promise
*/
static async find(type, id, projection = { empty: true }) {
const connectionURL = new URL(`https://mhw-db.com/${type}/${id}`);
if (projection.empty !== true) {
let p = JSON.stringify(projection);
connectionURL.searchParams.append("p", p);
}
return this.#fetchDB(connectionURL);
}
/**
* Searches for and returns several equipment entries in an array.
* @param {["armor"]} type Equipment type
* @param {{}} query Object to match entries with. Can use $gt, $lt, etc.
* @param {{}} projection {value: true, value: {value: true}}
* for all desired data.
* @returns {Promise<[{}]>} Array of Equipment
*/
static async search(type, query, projection = { empty: true }) {
const connectionURL = new URL(`https://mhw-db.com/${type}`);
let q = JSON.stringify(query);
connectionURL.searchParams.append("q", q);
if (projection.empty !== true) {
let p = JSON.stringify(projection);
connectionURL.searchParams.append("p", p);
}
return this.#fetchDB(connectionURL);
}
static async #fetchDB(connectionURL) {
let data;
await fetch(connectionURL)
.catch((err) => {
console.warn(`Error while connecting to MHW-db: ${err}`);
})
.then((res) => res.json())
.then((res) => {
data = res;
});
return data;
}
}
/**
* Searchbox controller
*/
class Search {
/**
* Connect the search controller to various inputs and an output.
* @param {MHW.Loadout} Hunter Reference to a current loadout.
* @param {string} nameID ID of a name filter text input.
* @param {string} rarityID ID of a rarity filter number input.
* @param {string} resultID ID of a container to fill
* with HTML mini card search results.
*/
constructor(Hunter, nameID, rarityID, resultID) {
this.#Hunter = Hunter;
this.#name = document.getElementById(nameID);
this.#rarity = document.getElementById(rarityID);
this.#result = document.getElementById(resultID);
}
#Hunter;
#selected = "";
#name;
#rarity;
#result;
/**
* Marks a body area as selected for modification.
* @param {["head", "chest", "gloves", "waist", "legs"]} toSelect Area to mark.
*/
select(toSelect) {
let elements = document.getElementsByClassName(
"MHW_MainGrid-equipment-item-selected"
);
for (const element of elements) {
element.classList.remove("MHW_MainGrid-equipment-item-selected");
}
if (!MHW.DataTypes.bodySections.includes(toSelect)) {
console.warn(`Invalid body section: "${toSelect}"`);
} else if (this.#selected !== toSelect) {
this.#selected = toSelect;
let thisElement = document.getElementById(toSelect);
thisElement.classList.add("MHW_MainGrid-equipment-item-selected");
console.log(`Change selected: ${toSelect}`);
} else {
this.#selected = "";
console.log(`Cleared selected`);
}
this.clearSearch();
}
/**
* Search for matching armor records of the currently selected type.
* Then fill the results box with recods.
*/
async search() {
if (this.#selected !== "") {
this.#name.value = this.#name.value.trim();
const query = {
type: this.#selected,
};
if (this.#rarity.value !== "") {
query.rarity = this.#rarity.value;
}
let result = await DataBase.search("armor", query, {
id: "true",
name: "true",
rarity: "true",
defense: {
base: "true",
},
"resistances.fire": "true",
"resistances.water": "true",
"resistances.ice": "true",
"resistances.thunder": "true",
"resistances.dragon": "true",
});
//Matches exist
if (result !== undefined && result.length !== 0) {
this.clearSearch();
console.log(result);
result.forEach((record) => {
if (
record.name.toLowerCase().includes(this.#name.value.toLowerCase())
) {
let card = this.#createMiniCard(record);
this.#result.appendChild(card);
}
});
} else {
this.#result.innerHTML = this.#createWarnCard("No results");
}
} else {
alert("Select an armor slot");
}
}
clearSearch() {
this.#result.replaceChildren("");
}
/**
* Creates a search result card from a returned armor record.
* @param {MHW.Loadout} record Requires name, id, defense base, resistances
* @returns {String} HTML mini card
*/
#createMiniCard(record) {
//TODO -- make this work
const card = document.createElement("div");
card.classList.add("MHW_MainGrid-searchResult-item");
let name = document.createElement("b");
name.innerHTML = `<i class="bi bi-arrow-left"></i>${record.name}`;
name.onclick = async () => {
await this.#Hunter.body.replaceItem(this.#selected, record.id); // TODO - make this
};
card.appendChild(name);
let def = document.createElement("span");
def.innerText = ` def: ${record.defense.base} `;
if (
record.defense.base > this.#Hunter.body[this.#selected].data.defense.base
) {
def.style.color = "green";
} else if (
record.defense.base < this.#Hunter.body[this.#selected].data.defense.base
) {
def.style.color = "maroon";
} else {
def.style.color = "grey";
}
card.appendChild(def);
//TODO maybe turn this into a may with the MHW.DataTypes class...
const resistDisplay = {
Fi: `${record.resistances.fire} `,
Wa: `${record.resistances.water} `,
Ic: `${record.resistances.ice} `,
Th: `${record.resistances.thunder} `,
Dr: `${record.resistances.dragon} `,
};
let resistList = document.createElement("div");
for (const resist in resistDisplay) {
let span = document.createElement("span");
span.innerText = `${resist}: ${resistDisplay[resist]}`;
span.style.color = MHW.DataTypes.elementColors[resist];
resistList.appendChild(span);
}
card.appendChild(resistList);
return card;
}
/**
* Creates an HTML warning card.
* @param {String} warning Text to display.
* @returns {String} HTML mini card
*/
#createWarnCard(warning) {
const card = document.createElement("div");
card.classList.add("MHW_MainGrid-searchResult-item");
let text = document.createElement("b");
text.innerText = warning;
card.appendChild(text);
return card.outerHTML;
}
}
class Storage {
/**
* Checks if a key is stored in persistent memory.
* @param {string} slot Key to check.
* @returns {boolean} Does data exist?
*/
static check(slot) {
let data = localStorage.getItem(`slot${slot}`);
return data !== null;
}
/**
* Save an entry to persistent memory.
* @param {string} slot Key to write to.
* @param {*} data Data to store.
*/
static saveTo(slot, data) {
localStorage.setItem(`slot${slot}`, JSON.stringify(data));
console.log(`Saved loadout to Slot${slot}`);
}
/**
* Retrieves an entry from peristent memory.
* @param {string} slot Key to read from.
* @returns {*} Stored value.
*/
static loadFrom(slot) {
let data = localStorage.getItem(`slot${slot}`);
if (data === null) {
throw `Could not load Slot${slot}: No entry found`;
} else {
return JSON.parse(data);
}
}
/**
* Saves a loadout to peristent memory.
* Assigns a unique id to each entry automatically.
* @param {*} name Name to save loadout with.
* @param {*} loadout Data to include in the entry.
*/
static saveLoadout(name, loadout) {
let loadouts = this.loadAllLoadouts();
let match = loadouts.findIndex((item) => item.name === name);
if (match !== -1) {
loadouts[match].loadout = loadout;
} else {
let newID = 0;
while (true) {
for (const item of loadouts) {
if (Number(newID) === Number(item.id)) {
newID++;
continue;
}
}
break;
}
loadouts.push({ name: name, id: newID, loadout: loadout });
loadouts.sort((a, b) => a.name.localeCompare(b.name));
}
this.saveTo("Loadouts", loadouts);
}
/**
* Retrieves a single loadout from persistent memory.
* @param {Number} id ID of loadout to retrieve.
* @returns {{name: String, id: Number, Loadout: MHW.Loadout}} Loadout
*/
static loadLoadout(id) {
let loadouts = this.loadAllLoadouts();
for (const item of loadouts) {
if (Number(item.id) === Number(id)) {
return item;
}
}
console.error(`Unable to find ID: ${id}`);
return undefined;
}
/**
* Retrieves the list containing all loadouts stored in persistent memory.
* @returns {[{name: String, id: Number, Loadout: MHW.Loadout}]} All saved Loadouts.
*/
static loadAllLoadouts() {
let loadouts;
if (this.check("Loadouts")) {
loadouts = this.loadFrom("Loadouts");
} else {
loadouts = [];
}
return loadouts;
}
/**
* Removes a loadout from persistent memory
* @param {Number} id ID of loadout to remove
*/
static removeLoadout(id) {
let loadouts = this.loadAllLoadouts();
for (let i = 0; i < loadouts.length; i++) {
if (Number(loadouts[i].id) === Number(id)) {
console.log("gottem?");
loadouts.splice(i);
}
}
console.log(`Removed ID: ${id}`);
this.saveTo("Loadouts", loadouts);
}
/**
* Clears everything stored in memory.
*/
static reset() {
localStorage.clear();
}
}
export { DataBase, Search, Storage };