shigatora / Small tiddies

// ==UserScript==
// @name         Small tiddies
// @namespace    http://tampermonkey.net/
// @version      2024-01-28
// @description  That's a secret
// @author       Vít Dolínek
// @include      http://*.grepolis.com/game/*
// @include      https://*.grepolis.com/game/*
// @match        https://zz12.grepolis.com/game*
// @icon         https://cdn.frankerfacez.com/emoticon/480945/4
// @require      https://unpkg.com/deepmerge@4.3.1/dist/umd.js
// @license      MIT
// @grant        none
// ==/UserScript==


const LS_ID = 'GPLGUtils_SavedTroops';
const LS_CB_ID = 'GPLGUtils_SavedTroops_CB';

(function() {
    'use strict';
    function initializeLS() {
        const shouldSave = localStorage.getItem(LS_CB_ID);
        const savedValues = localStorage.getItem(LS_ID);

        if (!savedValues) {
            localStorage.setItem(LS_ID, JSON.stringify({ "attack": {}, "support": {} }))
        }

        if (!shouldSave) {
            localStorage.setItem(LS_CB_ID, "true")
        }
    }

    initializeLS()

    function overwriteSaved(type, units, destinationId) {
        const savedValues = JSON.parse(localStorage.getItem(LS_ID));

        savedValues[type][destinationId] = units

        localStorage.setItem(LS_ID, JSON.stringify(savedValues));
    }


    function ObserverSEND_UNITS() {
        $.Observer(uw.GameEvents.command.send_unit).subscribe('SEND_UNITS', function (e, data) {
                if (data.sending_type === "revolt" || data.sending_type === "portal_attack_olympus") data.sending_type = "attack";
                if (data.sending_type === "portal_support_olympus") data.sending_type = "support";
                    const sentUnitsArray = {}

                for (var z in data.params) {
                    if (data.params.hasOwnProperty(z) && (data.sending_type !== "")) {
                        if (uw.GameData.units[z]) {
                            sentUnitsArray[z] = (sentUnitsArray[z] == undefined ? 0 : sentUnitsArray[z]);
                            sentUnitsArray[z] += data.params[z];
                        }
                    }
                }

            const shouldSaveValue = localStorage.getItem(LS_CB_ID);
            if (shouldSaveValue === "true") {
                overwriteSaved(data.sending_type, sentUnitsArray, data.target_id)
            }



        });
    }

    ObserverSEND_UNITS()

    window.GPLGUtils_SaveTroopsCbState = (element) => {
        localStorage.setItem(LS_CB_ID, element.checked ? "true" : "false");
    }

    window.GPLGUtils_ClearTroops = (id, type) => {
        const targetIdModel = GPWindowMgr.getOpenedWindows().find(e => e.getID() == id.replace("#gpwnd_", ""))
        if (!targetIdModel) return
        const targetId = targetIdModel.getHandler().target_id;

        const savedValues = JSON.parse(localStorage.getItem(LS_ID));

        delete savedValues[type][targetId]

        localStorage.setItem(LS_ID, JSON.stringify(savedValues));
    }



    function initializeSaveTroops(id, type) {
        const openedWindowElement = $(`#gpwnd_${id}`);
        const cbState = localStorage.getItem(LS_CB_ID)
        if (!openedWindowElement) {
            console.warn('Cant get opened window');
            return
        }

        if (document.getElementById(`saveTroops_wnd_${id}`) || document.getElementById(`clearTroops_wnd_${id}`)) {
            return;
        }


        openedWindowElement.append(`<input id="saveTroops_wnd_${id}" ${cbState === "true" && 'checked'} type="checkbox" onchange="window.GPLGUtils_SaveTroopsCbState(this)" /> Save troops`)
        openedWindowElement.append(`<span style="font-weight:bolder;cursor: pointer;color:brown;" onclick="window.GPLGUtils_ClearTroops('${`#gpwnd_${id}`}', '${type}')" /> Clear troops`)
    }


    function loadSavedTroops(id) {
    try {
        const targetIdModel = GPWindowMgr.getOpenedWindows().find(e => e.getID() == id)
        if (!targetIdModel) return
        const targetId = targetIdModel.getHandler().target_id;
        const action = targetIdModel.getHandler().action;
        const savedUnits = JSON.parse(localStorage.getItem(LS_ID));
                function appendUnitIcon(unit, count) {
                    $(`#gpwnd_${id}`).find(`.unit_icon40x40.${unit}`).parent().find('input').val(count)
                }

                for (var x in savedUnits[action][targetId]) {
                        if ((savedUnits[action][targetId][x] || 0) > 0) {
                            appendUnitIcon(x, savedUnits[action][targetId][x]);
                    }
                }

            } catch (error) { }
    }

    $(document).ajaxComplete(function (d, f, c) {
    if ("undefined" != typeof c) {
      d = c.url.replace(/\/game\/(.*)\?.*/, "$1");
      const urlParams = new URLSearchParams(c.url);
      var l =
        "frontend_bridge" !== d
          ? d
          : -1 < c.url.indexOf("json")
          ? JSON.parse(unescape(c.url).split("&")[3].split("=")[1]).window_type
          : d;
      if ("frontend_bridge" === d) {
        var m = WM.getWindowByType(l)[0];
      }
      $.each(Layout.wnd.getAllOpen(), function (c, d) {
        c = Layout.wnd.GetByID(d.getID());
        switch (c.getController()) {
          case "town_info":
            switch (c.getContext().sub) {
              case "town_info_attack":
              case "town_info_support":
                    initializeSaveTroops(c.getContext().main, c.getContext().sub === "town_info_attack" ? "attack" : "support");
                    loadSavedTroops(c.getContext().main)
                break;
            }
            break;
          default:
            break;
        }
      });
    }
  });


})();