Ahab / profile stats

// ==UserScript==
// @name         profile stats
// @namespace    torn
// @version      0.5
// @author       Ahab [1735214]
// @include      *www.torn.com/profiles.php?XID=*
// @grant        GM_addStyle
// @grant        GM.xmlHttpRequest
// @license      MIT
// @updateURL    https://openuserjs.org/meta/Ahab/profile_stats.meta.js
// ==/UserScript==

var apikey = "key"

GM_addStyle(`
#pstats {
  display: flex;
  padding: 5px;
}

#psettings {
  padding: 5px;
}

#statTable {
  border: 1px solid #ddd;
  flex: 50%;
  padding: 5px;
  margin: 5px;
  height: fit-content;
}

#pstatcont {
  border: 1px solid #ddd;
  flex: 50%;
  padding: 5px;
  margin: 5px;
}

.pheadings {
  font-weight: bold;
  text-decoration: underline;
  margin: 5px;
}

#pStat {
  padding: 5px;
  border: 1px solid #000;
  width: 5%;
  text-align: center;
  font-size: 12px;
  font-family: Arial;
  color: var(--default-color)
}

.pButton{
  margin:5px;
  background: transparent linear-gradient(180deg,#CCCCCC 0%,#999999 60%,#666666 100%) 0 0 no-repeat;
  box-sizing: border-box;
  border-radius: 5px;
  font-weight: 700;
  color: #333;
  text-shadow: 0 1px 0 #ffffff66;
  padding: 4px 8px;
  font-size: 14px;
  cursor: pointer;
  height: 65%;
  width: 10%;
  float: right;
  text-align: center;
  float: right;
  line-height: 0px;
}

.pButton:hover{
  background: transparent linear-gradient(180deg,#E5E5E5 0%,#BBBBBB 60%,#999999 100%) 0 0 no-repeat;
  color: #333;
}

.sButton{
  margin:5px;
  background: transparent linear-gradient(180deg,#CCCCCC 0%,#999999 60%,#666666 100%) 0 0 no-repeat;
  box-sizing: border-box;
  border-radius: 5px;
  font-weight: 700;
  color: #333;
  text-shadow: 0 1px 0 #ffffff66;
  padding: 4px 8px;
  font-size: 14px;
  cursor: pointer;
}

.nobull {
  list-style-type: none;
  padding-bottom: 3px;
 }

.pCheckbox {
  vertical-align: text-top;
  margin-right: 5px;
 }

.svg-icon {
  height: 16px;
  float: right;
  margin: 7px;
  padding-right: 8px;
}

.svg-icon path,
.svg-icon polygon,
.svg-icon rect {
  fill: #ffffff;
}
`)

var perstats = {"Attacking":{"attackswon": "Attacks Won","attackslost": "Attacks Lost","attacksdraw": "Attacks Stalemated","attacksassisted": "Attacks Assisted","defendswon": "Defends Won","defendslost": "Defends Lost","defendsstalemated": "Defends Stalemated","elo": "Elo","yourunaway": "Times Escaped","theyrunaway": "Foes Escaped","unarmoredwon": "Unarmored Fights Won","bestkillstreak": "Best Kill Streak","attackhits": "Hits","attackmisses": "Misses","attackdamage": "Total Damage Made","bestdamage": "Best Damage Made","onehitkills": "One Hit Kills","attackcriticalhits": "Critical Hits","roundsfired": "Rounds Fired","specialammoused": "Special Ammo Used","hollowammoused": "Hollow Ammo Used","tracerammoused": "Tracer Ammo Used","piercingammoused": "Piercing Ammo Used","incendiaryammoused": "Incendiary Ammo Used","attacksstealthed": "Attacks Stealthed","retals": "Retals","moneymugged": "Money Mugged","largestmug": "Largest Mug","itemslooted": "Items Looted","highestbeaten": "Highest Level Beaten","respectforfaction": "Total Respect","territoryjoins": "Territory Wall Joins","territorytime": "Territory Wall Time"},"Jobs":{"jobpointsused": "Job Points Used","trainsreceived": "Times Trained by Director"},"Trading":{"itemsbought": "Items Bought From Market","auctionswon": "Auctions Won","auctionsells": "Items Auctioned","itemssent": "Items Sent","pointsbought": "Points Bought"},"Jail":{"jailed": "Times Jailed","peoplebusted": "People Busted","failedbusts": "Failed Busts","peoplebought": "People Bailed","peopleboughtspent": "Bail Fees"},"Hospital":{"hospital": "Times In Hospital","medicalitemsused": "Medical Items Used","bloodwithdrawn": "Blood Withdrawn","reviveskill": "Revive Skill","revives": "Revives Given","revivesreceived": "Revives Received"},"Finishing Hits":{"heahits": "Heavy Artillery","machits": "Machine Guns","rifhits": "Rifles","smghits": "Sub Machine Guns","shohits": "Shotguns","pishits": "Pistols","grehits": "Temporary Weapons","piehits": "Piercing Wweapons","slahits": "Slashing Weapons","axehits": "Clubbing Weapons","chahits": "Mechanical Weapons","h2hhits": "Hand to Hand Hits"},"Communucation":{"mailssent": "Mails Sent","friendmailssent": "Mails to Friends","factionmailssent": "Mails to Faction","companymailssent": "Mails to Colleagues","spousemailssent": "Mails to Spouse","classifiedadsplaced": "Classified Ads Placed","personalsplaced": "Personals Placed"},"Criminal Offenses":{"organisedcrimes": "Organized Crimes"},"Bounties":{"bountiesplaced": "Bounties Placed","totalbountyspent": "Spent on Bounties",  "bountiescollected": "Bounties Collected","totalbountyreward": "Money Rewarded","bountiesreceived": "Bounties Received","receivedbountyvalue": "Value of Received Bounties"},"Items":{"cityfinds": "Items Found","itemsdumped": "Items Trashed","dumpfinds": "Items Found in Dump","booksread": "Books Read","boostersused": "Boosters Used","consumablesused": "Consumables Used","candyused": "Candy Eaten","alcoholused": "Alcohol Drunk","energydrinkused": "Energy Drinks Drunk","statenhancersused": "Stat Enhancers Used","virusescoded": "Viruses Coded"},"Travel":{"traveltimes": "Times Traveled","traveltime": "Time Spent Traveling","itemsboughtabroad": "Items Bought Abroad","attackswonabroad": "Attacks Won Abroad","defendslostabroad": "Defends Lost Abroad","argtravel": "Traveled to Argentina","mextravel": "Traveled to Mexico","dubtravel": "Traveled to United Arab Emirates","hawtravel": "Traveled to Hawaii","japtravel": "Traveled to Japan","lontravel": "Traveled to United Kingdom","soutravel": "Traveled to South Africa","switravel": "Traveled to Switzerland","chitravel": "Traveled to China","cantravel": "Traveled to Canada","caytravel": "Traveled to Cayman Islands"},"Drugs":{"drugsused": "Drugs Used","overdosed": "Times Overdosed","rehabs": "Rehabilitations","rehabcost": "Rehabilitation Fees","cantaken": "Cannabis Taken","exttaken": "Ecstasy Taken","kettaken": "Ketamine Taken","lsdtaken": "LSD taken","opitaken": "Opium Taken","pcptaken": "PCP Taken","shrtaken": "Shrooms Taken","spetaken": "Speed taken","victaken": "Vicodin Taken","xantaken": "Xanax Taken"},"Missions":{"missionscompleted": "Missions Completed","dukecontractscompleted": "Duke Contracts Completed","contractscompleted": "Contracts Completed","missioncreditsearned": "Mission Credits Earned"},"Racing":{"racingpointsearned": "Racing Points Earned","racesentered": "Races Entered","raceswon": "Races Won"},"Networth":{"networth": "Networth"},"Other":{"useractivity": "User Activity","activestreak": "Current Activity Streak","bestactivestreak": "Best Activity Streak","awards": "Awards","refills": "Energy Refills","nerverefills": "Nerve Refills","tokenrefills": "Token Refills","meritsbought": "Merits Bought","daysbeendonator": "Days Been a Donator"}}

if(localStorage.pState === undefined){
    localStorage.pState = 0
}
if(localStorage.apiStats === undefined){
    localStorage.apiStats = '["xantaken", "lsdtaken", "refills", "energydrinkused", "attackswon", "attackslost", "revives", "statenhancersused", "networth"]'
}

GM.xmlHttpRequest({
    method: "GET",
    headers: {'Cache-Control': 'no-cache'},
    url: "https://beta.tornstats.com/api/v1/"+apikey+"/spy/"+window.location.href.split("=")[1],
    onload: function(response) {
        var data = JSON.parse(response.responseText);
        console.log(data)
        var statNames = ['Defense','Dexterity','Speed','Strength','Total']
        var pstatData = ""
        var spyData = ""
        var spyTime = ""
        for(var pstats in data['compare']['data']){
            if(data['compare']['data'][pstats]['difference'] > 0){
                pstatData += '<tr id="trpStat"><td id="pStat">'+pstats+'</td><td id="pStat">'+data['compare']['data'][pstats]['amount'].toLocaleString()+'</td><td id="pStat" style="color: green">+'+data['compare']['data'][pstats]['difference'].toLocaleString()+'</td></tr>'
            }
            else if(data['compare']['data'][pstats]['difference'] < 0){
                pstatData += '<tr id="trpStat"><td id="pStat">'+pstats+'</td><td id="pStat">'+data['compare']['data'][pstats]['amount'].toLocaleString()+'</td><td id="pStat" style="color: red">'+data['compare']['data'][pstats]['difference'].toLocaleString()+'</td></tr>'
            }
            else{
                pstatData += '<tr id="trpStat"><td id="pStat">'+pstats+'</td><td id="pStat">'+data['compare']['data'][pstats]['amount'].toLocaleString()+'</td><td id="pStat">'+data['compare']['data'][pstats]['difference'].toLocaleString()+'</td></tr>'
            }
        }
        if(data['spy']['status'] == true){
            for(var stats in statNames){
                if(data['spy']['delta'+statNames[stats]] > 0){
                    spyData += '<tr id="trpStat"><td id="pStat">'+statNames[stats]+'</td><td id="pStat">'+data['spy'][statNames[stats].toLowerCase()].toLocaleString()+'</td><td id="pStat" style="color: green">+'+data['spy']['delta'+statNames[stats]].toLocaleString()+'</td></tr>'
                }
                else if(data['spy']['delta'+statNames[stats]] < 0){
                    spyData += '<tr id="trpStat"><td id="pStat">'+statNames[stats]+'</td><td id="pStat">'+data['spy'][statNames[stats].toLowerCase()].toLocaleString()+'</td><td id="pStat" style="color: red">'+data['spy']['delta'+statNames[stats]].toLocaleString()+'</td></tr>'
                }
                else{
                    spyData += '<tr id="trpStat"><td id="pStat">'+statNames[stats]+'</td><td id="pStat">'+data['spy'][statNames[stats].toLowerCase()].toLocaleString()+'</td><td id="pStat">'+data['spy']['delta'+statNames[stats]].toLocaleString()+'</td></tr>'
                }
            }
            spyTime = 'Spy date - '+data['spy']['difference']
        }
        $("div[class*='medals-wrapper']").before('<div id="pstatTitle" class="title-black top-round"><span>Personal Stats | '+spyTime+'</span><span><input id="pScreen" class="pButton" type="submit" value="Settings"></span><span id="pstate"><svg xmlns="http://www.w3.org/2000/svg" class="svg-icon" viewBox="0 0 20 32"><path d="M16 10l-6 6-6-6-4 4 10 10 10-10-4-4z"></path></svg></span></div><div id=pstats class="cont-gray bottom-round" style="display: flex;"><table id=statTable style="width: 30%; border-collapse: collapse"><tbody>'+pstatData+'</tbody></table><table id=statTable style="width: 30%; border-collapse: collapse"><tbody>'+spyData+'</tbody></table></div><div id="psettings" class="cont-gray bottom-round" style="display: none;"></div>')
        for(var heading in perstats){
            $("div[id*='psettings']").append('<div id="pstatcont" name="'+heading+'"><div class="pheadings">'+heading+'</div></div>')
            for(var stat in perstats[heading]){
                $("div[name*='"+heading+"']").append('<li class="nobull"><input type="checkbox" id="'+stat+'" value="'+stat+'" class="pCheckbox"><label for="'+stat+'"  value="'+stat+'" class="pLabel">'+perstats[heading][stat]+'</label></li>')
            }
        }
        $("div[id*='psettings']").append('<input id="statsSubmit" type="submit" class="sButton" value="SUBMIT"></input>')
        for(var apiStat in JSON.parse(localStorage.apiStats)){
            $('input[value="'+JSON.parse(localStorage.apiStats)[apiStat]+'"]').prop('checked', true)
        }
        $('input[type="checkbox"]').on('click', function(event) {
            addRem(event.target.value)
        })
        $('input[id^="pScreen"]').on('click', function(event) {
            if($('div[id*="pstats"]')[0].attributes[2].value == "display: none;" && $('div[id*="psettings"]')[0].attributes[2].value == "display: none;" ){
                $('div[id*="psettings"]').toggle()
                localStorage.pState = 0
                icons(2)
            }
            else{
                $('div[id*="pstats"]').toggle()
                $('div[id*="psettings"]').toggle()
                localStorage.pState = 0
            }
            if ($('div[id="pstatTitle"] span')[0].innerText == 'Personal Stats | '+spyTime || $('div[id="pstatTitle"] span')[0].innerText == 'Personal Stats |') {
                $('div[id="pstatTitle"] span')[0].innerText = 'Personal Stats Settings';
            } else {
                $('div[id="pstatTitle"] span')[0].innerText = 'Personal Stats | '+spyTime;
            }
        })
        $('input[id="statsSubmit"]').on('click', function(event) {
            updateSettings()
        })
        $('div[id^="pstatTitle"]').on('click', function(event) {
            if(event.target.className != 'pButton'){
                if($('div[id*="psettings"]')[0].attributes[2].value == "display: block;"){
                    $('div[id*="psettings"]').toggle()
                    $('div[id="pstatTitle"] span')[0].innerText = 'Personal Stats | '+spyTime;
                }
                else{
                    $('div[id*="pstats"]').toggle()
                }
                icons(2)
            }
        })
        if(localStorage.pState == 1){
            icons(1)
        }
    }})

function updateSettings(){
    var stored = JSON.parse(localStorage.apiStats)
    GM.xmlHttpRequest({
        method: "GET",
        url: "https://www.tornstats.com/api/v1/"+apikey+"/settings&comparespy=1&comparepersonal=1&personalstats="+stored.toString(),
        onload: function(response) {
            console.log(response)
            location.reload();
        }
    })
}

function icons(p){
    if(p == 1){
        $('div[id*="pstats"]').toggle()
        $('span[id*="pstate"]')[0].id = 'pstate1'
    }else{
        if($('span[id*="pstate"]')[0].id == 'pstate'){
            $('span[id*="pstate"]')[0].innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" class="svg-icon" viewBox="0 0 14 32"><path d="M4 6l-4 4 6 6-6 6 4 4 10-10L4 6z"></path></svg>'
            $('span[id*="pstate"]')[0].id = 'pstate1'
            localStorage.pState = 1
        }
        else{
            $('span[id*="pstate"]')[0].innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" class="svg-icon" viewBox="0 0 20 32"><path d="M16 10l-6 6-6-6-4 4 10 10 10-10-4-4z"></path></svg>'
            $('span[id*="pstate"]')[0].id = 'pstate'
            localStorage.pState = 0
        }
    }
}

function addRem(value){
    var stored = JSON.parse(localStorage.apiStats)
    if(stored.indexOf(value) != -1){
        var t = stored.indexOf(value)
        stored.splice(t, 1);
        localStorage.apiStats = JSON.stringify(stored)
    }
    else if(stored.indexOf(value) == -1){
        stored.push(value)
        localStorage.apiStats = JSON.stringify(stored)
    }
}