let fetch = require('node-fetch')
function initialCap(string) {
	string = string.split(" ")
	for (i = 0; i < string.length; i++) {
		firstChar = string[i].charAt(0);
		string[i] = string[i].replace(firstChar, firstChar.toUpperCase());
		//credit for the above 2 lines goes to HairyOtter07
	}
	string = string.join(" ")
	return string
}
const SRClevels = require("../SRCAPI/levels.json")
const SRCvariables = require("../SRCAPI/variables.json")
const SRCshrines = require("../SRCAPI/shrines.json")
exports.run = (client, message, splitMessage, makeEmbed) => {
  message.channel.send("Please hold on! Fetching data...").then(msgE=>{
    var category = "824mrqg2"
    if (splitMessage[3] && (splitMessage[3] == "100" || splitMessage[3] == "100%")) {
        category = "9d8jg53k"
    }
    if (splitMessage[3] && splitMessage[3].toLowerCase() == "nmg") {
        category = "zd3op4nd"
    }
    var input = splitMessage.splice(1, 2).join("_").toLowerCase()
    try {
        var shrine = SRCshrines[input].id
        var region = SRCvariables[SRCshrines[input].region]
        var level = SRClevels[SRCshrines[input].region]
        var dispRegion = (SRCshrines[input].region).replace("_", " ")
        var dlc = ["revisit", "daruk", "mipha", "revali", "urbosa"]
        if (dlc.includes(dispRegion)) {
            if (dispRegion == "revisit") {
                dispRegion = "Great Plateau Revisit Shrines"
            } else {
                dispRegion = dispRegion + "\'s Song Shrines"
            }
        } else {
            dispRegion = dispRegion + " tower region"
        }
        var dispShrine = (input.replace("_", " "))

        fetch("https://www.speedrun.com/api/v1/leaderboards/76rqjqd8/level/" + level + "/" + category + "?var-" + region + "=" + shrine).then(res => res.json())
            .then(res => {
                try {
                    var userURI = res.data.runs[0].run.players[0].uri //we have to do another fetch to get the name
                    var time = res.data.runs[0].run.times.primary_t.toFixed(3)
                    if (time >= 60) {
                        var m = Math.floor(time / 60)
                        var s = time % 60
                        if (s >= 10) {
                            time = m + ":" + s.toFixed(3)
                        } else {
                            time = m + ":0" + s.toFixed(3)
                        }

                    }
                    var weblink = res.data.runs[0].run.weblink
                    var runDesc = res.data.runs[0].run.comment
                    var submissionDate = (res.data.runs[0].run.submitted).substring(0, 10)
                    var verifierURI = res.data.runs[0].run.status.examiner
                    var verificationDate = res.data.runs[0].run.status['verify-date'].substring(0, 10)
                    if (runDesc == null) {
                        runDesc = "No Description Entered"
                    } else {
                        runDesc = "" + runDesc
                    }
                    fetch(userURI).then(res => res.json())
                        .then(res => {
                            var user = res.data.names.international
                            var userCountry = ""
                            if (res.data.location != null) {
                                userCountry = res.data.location.country.code
                                user = " :flag_" + userCountry + ": " + user
                            }


                            fetch("https://www.speedrun.com/api/v1/users/" + verifierURI).then(res => res.json())
                                .then(res => {
                                    var verifier = res.data.names.international
                                    var verifierCountry = ""
                                    if (res.data.location != null) {
                                        verifierCountry = res.data.location.country.code
                                        verifier = " :flag_" + verifierCountry + ": " + verifier
                                    }

                                    const embed1 = {
                                        "color": "00ff00",
                                        author: {
                                          "name": "Komali Bot 2",
                                          "icon_url": client.user.avatarURL()
                                        },
                                        "title": initialCap(dispShrine) + " (" + initialCap(dispRegion) + ")",
                                        "description": "[World Record is **" + time + "** by " + user + "](" + weblink + ")\nSubmitted on " + submissionDate + "\nVerified by " + verifier + " on " + verificationDate,
                                        fields: [{
                                            "name": "Run Description",
                                            "value": runDesc
                                        }, ],


                                    }
                                    msgE.edit("Data Succesfully Fetched", {
                                        embed: embed1
                                    })


                                })


                        })

                } catch (err) {
                  
                    msgE.edit("An Error Occured...", {embed: makeEmbed("No Run Exists for this Category!")})
                }
            })
    } catch (err) {
        msgE.edit("An Error Occured...", {embed: makeEmbed("Please Specify a Valid Shrine!")})
    }
    })
}