using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.SDK3.Components;
using VRC.SDK3.StringLoading;

// ZeroInventory world viewer.
//
// Udon cannot build a URL at runtime and cannot send POST requests, so the only
// network access a world has is loading a URL that was either baked into the
// world or typed into a VRCUrlInputField. This component loads the personal
// read-only URL from the console and shows every character it returns; picking
// a character happens locally and needs no further request.
//
// Everything that writes (pairing, linking, moving items) stays on the website.
public class ZeroInventoryClient : UdonSharpBehaviour
{
    [Header("ZeroInventory")]
    public string worldName = "My VRChat world";
    public string apiBaseUrl = "https://zeroinventory.zerotwo.eu.org";
    public VRCUrlInputField urlInput;

    [Header("World identity (filled by the editor script)")]
    public string worldBlueprintId = "";
    public VRCUrl worldRegisterUrl;

    [Header("Sync")]
    public float pollSeconds = 10f;
    public float playerRefreshSeconds = 2f;

    [Header("Runtime status, read by ZeroInventoryHud")]
    public string statusMessage = "Paste your world URL and press Connect.";
    public string lastError = "";
    public bool connected = false;
    public bool loading = false;
    public bool polling = false;
    public int characterCount = 0;
    public int selectedIndex = 0;
    public string characterName = "";
    public string characterStatus = "";
    public string inventoryText = "No data yet.";
    public int playerCount = 0;
    public string[] playerNames;
    public string[] feedLines;

    private float nextPlayerRefresh = 0f;

    private VRCUrl feedUrl;
    private string[] characterIds;
    private string[] characterNames;
    private string[] characterStatuses;
    private bool registering = false;
    private bool registered = false;

    void Start()
    {
        feedLines = new string[0];
        characterIds = new string[0];
        characterNames = new string[0];
        characterStatuses = new string[0];
        playerNames = new string[0];
        RegisterWorld();
        RefreshPlayers();
    }

    // ---------- players in the instance ----------

    // VRChat exposes the instance roster to Udon, so the panel can list who is
    // here right now without asking the server. This is local to each client.
    void Update()
    {
        if (Time.time < nextPlayerRefresh) return;
        nextPlayerRefresh = Time.time + playerRefreshSeconds;
        RefreshPlayers();
    }

    private void RefreshPlayers()
    {
        int count = VRCPlayerApi.GetPlayerCount();
        VRCPlayerApi[] players = new VRCPlayerApi[count];
        VRCPlayerApi.GetPlayers(players);

        string[] names = new string[players.Length];
        for (int index = 0; index < players.Length; index++)
        {
            VRCPlayerApi player = players[index];
            if (player == null)
            {
                names[index] = "";
                continue;
            }
            string name = player.displayName;
            if (player.isLocal) name = name + " (you)";
            names[index] = name;
        }
        playerNames = names;
        playerCount = names.Length;
    }

    // The world tells the console who it is on its first request. The editor
    // script reads the blueprint id out of the VRChat pipeline manager and
    // builds the URL, because Udon cannot build one at runtime.
    private void RegisterWorld()
    {
        if (registered || registering) return;
        if (worldRegisterUrl == null) return;
        registering = true;
        VRCStringDownloader.LoadUrl(worldRegisterUrl, this);
    }

    void OnDisable()
    {
        // Stop polling while the object is inactive; the pasted URL is kept so a
        // re-enabled client can poll again without asking for it.
        polling = false;
    }

    void OnEnable()
    {
        if (connected && !polling && feedUrl != null)
        {
            polling = true;
            SchedulePoll();
        }
    }

    // ---------- connection ----------

    public void ConnectFromInput()
    {
        if (loading) return;
        if (urlInput == null)
        {
            lastError = "Assign a VRCUrlInputField to the client.";
            return;
        }
        VRCUrl url = urlInput.GetUrl();
        if (url == null || VRCUrl.IsNullOrEmpty(url))
        {
            lastError = "Paste your world URL first.";
            return;
        }
        feedUrl = url;
        connected = true;
        lastError = "";
        statusMessage = "Loading characters...";
        polling = true;
        RequestFeed();
    }

    public void Disconnect()
    {
        polling = false;
        connected = false;
        loading = false;
        feedUrl = VRCUrl.Empty;
        characterCount = 0;
        selectedIndex = 0;
        characterName = "";
        characterStatus = "";
        inventoryText = "Disconnected.";
        feedLines = new string[0];
        characterIds = new string[0];
        characterNames = new string[0];
        characterStatuses = new string[0];
        lastError = "";
        statusMessage = "Paste your world URL and press Connect.";
    }

    public void RefreshNow()
    {
        if (!connected || loading) return;
        statusMessage = "Refreshing...";
        RequestFeed();
    }

    // ---------- polling ----------

    private void RequestFeed()
    {
        loading = true;
        VRCStringDownloader.LoadUrl(feedUrl, this);
    }

    private void SchedulePoll()
    {
        if (!polling) return;
        float seconds = pollSeconds;
        // VRChat serves one string download per five seconds; polling faster
        // only queues requests.
        if (seconds < 5f) seconds = 5f;
        SendCustomEventDelayedSeconds(nameof(PollTick), seconds);
    }

    public void PollTick()
    {
        if (!polling) return;
        if (loading)
        {
            SchedulePoll();
            return;
        }
        if (!connected) return;
        RequestFeed();
    }

    public override void OnStringLoadSuccess(IVRCStringDownload result)
    {
        if (registering)
        {
            // Reply to the world registration; there is nothing to parse.
            registering = false;
            registered = true;
            return;
        }

        loading = false;
        lastError = "";
        ApplyFeed(result.Result);
        SchedulePoll();
    }

    public override void OnStringLoadError(IVRCStringDownload result)
    {
        if (registering)
        {
            registering = false;
            return;
        }

        loading = false;
        int code = result.ErrorCode;
        if (code == 401 || code == 404)
        {
            lastError = "That world URL is not valid or it expired. Get a new one on the website.";
            Disconnect();
            return;
        }
        if (code == 403)
        {
            lastError = "Access denied for this world URL.";
        }
        else if (code > 0)
        {
            lastError = "Sync failed (HTTP " + IntToString(code) + ").";
        }
        else
        {
            lastError = "Could not reach the ZeroInventory server.";
        }
        statusMessage = "Waiting to retry.";
        SchedulePoll();
    }

    // ---------- feed ----------

    private void ApplyFeed(string text)
    {
        if (text == null || text == "")
        {
            lastError = "The world URL returned no data.";
            return;
        }

        feedLines = SplitLines(text);

        int count = 0;
        for (int index = 0; index < feedLines.Length; index++)
        {
            if (!StartsWith(feedLines[index], "CHAR|")) continue;
            if (!MatchesWorld(feedLines[index])) continue;
            count++;
        }

        characterIds = new string[count];
        characterNames = new string[count];
        characterStatuses = new string[count];

        int slot = 0;
        for (int index = 0; index < feedLines.Length; index++)
        {
            string line = feedLines[index];
            if (!StartsWith(line, "CHAR|")) continue;
            if (!MatchesWorld(line)) continue;
            characterIds[slot] = Field(line, 1);
            characterNames[slot] = Field(line, 2);
            characterStatuses[slot] = Field(line, 3);
            slot++;
        }

        characterCount = count;
        if (count == 0)
        {
            selectedIndex = 0;
            characterName = "";
            characterStatus = "";
            inventoryText = "No characters are assigned to this account on this server.";
            statusMessage = "Synced.";
            return;
        }

        if (selectedIndex >= count) selectedIndex = 0;
        SelectCharacter(selectedIndex);
        statusMessage = "Synced.";
    }

    public void SelectCharacter(int index)
    {
        if (index < 0 || index >= characterCount) return;
        selectedIndex = index;
        characterName = characterNames[index];
        characterStatus = characterStatuses[index];
        string id = characterIds[index];

        string output = characterName + "  (" + characterStatus + ")";
        for (int pass = 0; pass < 2; pass++)
        {
            for (int lineIndex = 0; lineIndex < feedLines.Length; lineIndex++)
            {
                string line = feedLines[lineIndex];
                if (Field(line, 1) != id) continue;

                if (pass == 0 && StartsWith(line, "CONTAINER|"))
                {
                    output = output + "\n" + Field(line, 3) + "  " + Field(line, 7) + "/" + Field(line, 6);
                }
                else if (pass == 1 && StartsWith(line, "ITEM|"))
                {
                    output =
                        output
                        + "\n"
                        + Field(line, 4)
                        + " "
                        + Field(line, 5)
                        + "  x"
                        + Field(line, 10)
                        + "  ["
                        + Field(line, 6)
                        + "]";
                }
            }
        }

        inventoryText = output;
    }

    public void NextCharacter()
    {
        if (characterCount == 0) return;
        int next = selectedIndex + 1;
        if (next >= characterCount) next = 0;
        SelectCharacter(next);
    }

    public void PreviousCharacter()
    {
        if (characterCount == 0) return;
        int previous = selectedIndex - 1;
        if (previous < 0) previous = characterCount - 1;
        SelectCharacter(previous);
    }

    // ---------- helpers for the HUD ----------

    // CHAR|id|name|status|player|<worldIds, comma separated>. A character with
    // no world shows in every world; otherwise it shows in each world it is
    // assigned to. Udon has no string.Split for arbitrary separators here, so
    // the list is walked by hand.
    private bool MatchesWorld(string line)
    {
        if (worldBlueprintId == "") return true;
        string list = Field(line, 5);
        if (list == "") return true;

        int start = 0;
        for (int index = 0; index <= list.Length; index++)
        {
            if (index < list.Length && list[index] != ',') continue;
            if (index - start == worldBlueprintId.Length && SameRange(list, start, worldBlueprintId))
            {
                return true;
            }
            start = index + 1;
        }
        return false;
    }

    private static bool SameRange(string source, int offset, string value)
    {
        for (int index = 0; index < value.Length; index++)
        {
            if (source[offset + index] != value[index]) return false;
        }
        return true;
    }

    public string StatusLine()
    {
        string state = connected ? "connected" : "not connected";
        string output = "ZeroInventory - " + state;
        if (characterCount > 0)
        {
            output =
                output
                + "  char "
                + IntToString(selectedIndex + 1)
                + "/"
                + IntToString(characterCount)
                + "  "
                + characterName;
        }
        return output;
    }

    public string Field(string line, int index)
    {
        if (line == null) return "";
        int start = 0;
        int current = 0;
        while (current < index)
        {
            int next = line.IndexOf("|", start);
            if (next < 0) return "";
            start = next + 1;
            current++;
        }
        int end = line.IndexOf("|", start);
        if (end < 0) return line.Substring(start);
        return line.Substring(start, end - start);
    }

    private string[] SplitLines(string text)
    {
        if (text == null || text == "") return new string[0];
        int count = 1;
        int cursor = 0;
        while (true)
        {
            int next = text.IndexOf("\n", cursor);
            if (next < 0) break;
            count++;
            cursor = next + 1;
        }
        string[] lines = new string[count];
        cursor = 0;
        for (int index = 0; index < count; index++)
        {
            int next = text.IndexOf("\n", cursor);
            if (next < 0)
            {
                lines[index] = text.Substring(cursor);
                break;
            }
            lines[index] = text.Substring(cursor, next - cursor);
            cursor = next + 1;
        }
        return lines;
    }

    private bool StartsWith(string value, string prefix)
    {
        if (value == null) return false;
        if (value.Length < prefix.Length) return false;
        return value.Substring(0, prefix.Length) == prefix;
    }

    public string IntToString(int value)
    {
        if (value == 0) return "0";
        bool negative = value < 0;
        int remaining = value;
        if (negative) remaining = -remaining;
        string digits = "";
        while (remaining > 0)
        {
            int digit = remaining % 10;
            digits = DigitChar(digit) + digits;
            remaining = remaining / 10;
        }
        if (negative) return "-" + digits;
        return digits;
    }

    private string DigitChar(int digit)
    {
        if (digit == 0) return "0";
        if (digit == 1) return "1";
        if (digit == 2) return "2";
        if (digit == 3) return "3";
        if (digit == 4) return "4";
        if (digit == 5) return "5";
        if (digit == 6) return "6";
        if (digit == 7) return "7";
        if (digit == 8) return "8";
        return "9";
    }
}
