--[[
================================================================================================================================
This code was made by JSD
================================================================================================================================
]]--

local M = {}
M.type = "auxiliary"
M.relevantDevice = nil

local htmlTexture = require("htmlTexture")

local RGB = nil
local htmlPath = nil

local updateTimer = 0
local updateFPS = 30
local invFPS = 1 / updateFPS
local rgb_set = 1
local rgb_pattern = 1
local rgb_pattern_name = "RGB"

local function init(jbeamData)
    RGB = jbeamData.materialName
    htmlPath = jbeamData.htmlPath
    local width = jbeamData.textureWidth or 256
    local height = jbeamData.textureHeight or 256

    htmlTexture.create(RGB, htmlPath, width, height, updateFPS, "automatic")
    htmlTexture.call(RGB, "update", rgb_set)
end

local function update(rgb_set, jbeamData)
    htmlTexture.call(RGB, "update", rgb_set)
end

local function color_name_forward()
    local color_names_forward = {
        "RGB Fade 1", "RGB Fade 2", "RGB Fade 3", "RGB Fade 4", "RGB Flash (Slow)", "RGB Flash (Medium)", "RGB Flash (Fast)", "Twinkle", "Red", "Blue", "Green", "Cyan", "Orange", "Violet", "Indigo", "Purple",
        "Pink", "Yellow", "White", "Off"
    }
    rgb_pattern_name = color_names_forward[rgb_pattern]
end

local function color_name_backwards()
    local color_names_backwards = {
        "RGB Fade 1", "RGB Fade 2", "RGB Fade 3", "RGB Fade 4", "RGB Flash (Slow)", "RGB Flash (Medium)", "RGB Flash (Fast)", "Twinkle", "Red", "Blue", "Green", "Cyan", "Orange", "Violet", "Indigo", "Purple",
        "Pink", "Yellow", "White", "Off"
    }
    rgb_pattern_name = color_names_backwards[rgb_pattern]
end

-- Functions to toggle the variable
local function toggleRgb_forward()
    rgb_set = rgb_set + 1
    if rgb_set >= 21 then
        rgb_set = 1
    end
    rgb_pattern = rgb_pattern + 1
    if rgb_pattern >= 21 then
        rgb_pattern = 1
    end
    update(rgb_set, jbeamData)
    color_name_forward()
    guihooks.message("Starlights color changed! Now showing: " .. rgb_pattern_name) 
end

local function toggleRgb_backwards()
    rgb_set = rgb_set - 1
    if rgb_set <= 0 then
        rgb_set = 20
    end
    rgb_pattern = rgb_pattern - 1
    if rgb_pattern <= 0 then
        rgb_pattern = 20
    end
    update(rgb_set, jbeamData)
    color_name_backwards()
    guihooks.message("Starlights color changed! Now showing: " .. rgb_pattern_name) 
end

M.init = init
M.toggleRgb_forward = toggleRgb_forward
M.toggleRgb_backwards = toggleRgb_backwards

return M
