sedemo = {}

local json = require("json")
local SolarEngineSDK = require("SolarEngineSDK")

sedemo.startRun = function()
    sedemo.loadUIElements()
end

local widget = require("widget")  -- 引入 Solar2D 官方 UI 库


sedemo.loadUIElements = function()

    local eventList = {
        "setSuper", "unsetSuper", "clearSuper",
        "preinit", "init", "login", "logout", "setVisitorId",
        "getDistinctId", "getAccountId", "getVisitorId", "setChannel",
        "setGDPRArea", "setGaid", "setOaid", "setPresetEvent", "track",
        "trackPurchase", "trackAdImp", "trackAdClick", "trackAtt",
        "trackRegister", "trackLogin", "trackOrder", "trackFirst",
        "appEngagement", "eventStart", "eventFinish", "reportImmediately", "getAttributionData",
        "userInit", "userUpdate", "userAdd", "userUnset", "userAppend", "userDelete",
        "getPresetProperties", "setRemoteConfigEvent", "setRemoteConfigUser", "fastFetchRC", "fastAllFetchRC", "asyncFetchRC", "asyncAllFetchRC"
    }

    ------------------------------------------------
    -- ScrollView 容器
    ------------------------------------------------
    local scrollView = widget.newScrollView({
        x = display.contentCenterX,
        y = display.contentCenterY,
        width = display.contentWidth,
        height = display.contentHeight - 100, -- 留出顶部/底部空间
        hideBackground = false,
        backgroundColor = { 0.05, 0.05, 0.05, 0.1 },
        horizontalScrollDisabled = true, -- 禁止横向滑动
        verticalScrollDisabled = false,
        hideScrollBar = false
    })

    ------------------------------------------------
    -- 布局参数
    ------------------------------------------------
    local yStart = 30
    local colCount = 2
    local spacingY = 35
    local spacingX = 100
    local buttonWidth = 90
    local buttonHeight = 28
    local paddingLeft = 50

    ------------------------------------------------
    -- 动态创建按钮
    ------------------------------------------------
    for i = 1, #eventList do
        local col = ((i - 1) % colCount)
        local row = math.floor((i - 1) / colCount)

        local x = paddingLeft + (col * spacingX)
        local y = yStart + row * spacingY

        local label = eventList[i]

        local button = widget.newButton({
            x = x + 60,
            y = y,
            width = buttonWidth,
            height = buttonHeight,
            label = label,
            labelColor = { default = { 1, 1, 1 }, over = { 0.9, 0.9, 0.9 } },
            shape = "roundedRect",
            cornerRadius = 8,
            fillColor = {
                default = { 0.55, 0.8, 0.95, 1 }, -- 浅蓝
                over = { 0.1, 0.45, 0.75, 1 }
            },
            strokeColor = {
                default = { 1, 1, 1, 0.2 },
                over = { 1, 1, 1, 0.3 }
            },
            strokeWidth = 1,
            font = native.systemFontBold,
            fontSize = 10,
            onRelease = function()
                local funcName = eventList[i]
                local f = loadstring("sedemo." .. funcName .. "()")
                if type(f) == "function" then
                    f()
                else
                    print("[SolarEngine] ⚠️ " .. funcName .. " is not a function")
                end
            end
        })

        -- 把按钮插入 scrollView
        scrollView:insert(button)
    end
end



function sedemo.preinit()
    print("preinit called")

    SolarEngineSDK.preinit("11111")

end

function sedemo.init()
    print("init called")
    SolarEngineSDK.setInitCompletedCallback(function(code)
        if code == 0 then
            print("[SolarEngineSDK] 初始化成功")
        else
            print("[SolarEngineSDK] 初始化失败，错误码:", code)
        end
    end)
    SolarEngineSDK.setAttributionCallback(function(code, data)
        print("attributionCallback called")
        print("[SolarEngineSDK]code:" .. code)
        print("[SolarEngineSDK]data:" .. data)
    end)

    local params = {
        appKey = "111",
        logEnabled = false,
        isDebugModel = true,
        enableDeferredDeeplink = true,
        remoteConfig = {
            enable = true,
            mergeType = SolarEngineSDK.mergeType.byUser,
            customIDProperties = {
                CustomIDkey = "value",
            },
            customIDUserProperties = {
                CustomUserIDkey = "value",
            },
            customIDEventProperties = {
                CustomEventIDkey = "value",
            }


        } 
    }
    SolarEngineSDK.setDeferredDeepLinkCallback(function(code, deeplinkInfo)
        print("deferredDeeplinkCallback called")
        print("code:" .. code)
        print("data:" .. json.encode(deeplinkInfo))
        if deeplinkInfo then
            print("turlId:", deeplinkInfo.turlId)
            print("sedpLink:", deeplinkInfo.sedpLink)
            print("sedpUrlscheme:", deeplinkInfo.sedpUrlscheme)
        else
            print("no deeplinkInfo returned")
        end
    end)
    SolarEngineSDK.setDeepLinkCallback(function(code, deepLinkInfo)
        print("deepLinkCallback called")
        print("code:" .. code)
        print("data:" .. json.encode(deepLinkInfo))
        if deepLinkInfo then
            print("turlId:", deepLinkInfo.turlId)
            print("sedpLink:", deepLinkInfo.sedpLink)
            print("from:", deepLinkInfo.from)
            print("customParams:", deepLinkInfo.customParams)
        else
            print("no deepLinkInfo returned")
        end
    end)
    SolarEngineSDK.requestTrackingAuthorization(function(status)
        print("追踪授权状态:", status)
    end)
    SolarEngineSDK.initSdk(params);

    sedemo. rcDefaultConfig();

end

function sedemo.login()
    print("login called")
    SolarEngineSDK.login("loginid")
end

function sedemo.logout()
    print("logout called")
    SolarEngineSDK.logout()
end

function sedemo.setVisitorId()
    print("setVisitorID called")
    SolarEngineSDK.setVisitorId("visitorid")
end

function sedemo.getDistinctId()
    print("getDistinctId called")
    local distinctId = SolarEngineSDK.getDistinctId()
    print("Distinct ID:", distinctId)
end
function sedemo.getAccountId()
    print("getAccountId called")
    local id = SolarEngineSDK.getAccountId()
    print("id:" .. id)
end
function sedemo.getVisitorId()
    print("getVisitorID called")
    local id = SolarEngineSDK.getVisitorId()
    print("id:" .. id)
end
function sedemo.setChannel()
    print("setChannel called")
    SolarEngineSDK.setChannel("channel")
end
function sedemo.setGDPRArea()
    print("setGDPRArea called")
    SolarEngineSDK.setGDPRArea(true)
end
function sedemo.setGaid()
    print("setGaid called")
    SolarEngineSDK.setGaid("gaid")
end
function sedemo.setOaid()
    print("setOaid called")
    SolarEngineSDK.setOaid("oaid")
end
function sedemo.setPresetEvent()
    print("setPresetEvent called")
    local properties = {
        Presetkey = "value",
    }
    SolarEngineSDK.setPresetEvent(SolarEngineSDK.eventType.All, properties)
    SolarEngineSDK.setPresetEvent(SolarEngineSDK.eventType.Start, nil)

end
function sedemo.track()
    print("track called")

    SolarEngineSDK.track("game_start", {
        game_mode = "single_player",
        difficulty = "normal",
        player_level = 5
    })

end
function sedemo.reportImmediately()
    print("reportImmediately called")
    SolarEngineSDK.reportEventImmediately()
end

function sedemo.getAttributionData()
    print("getAttributionData called")
    local value = SolarEngineSDK.getAttributionData()
    print("getAttributionData : " .. value)

    print("getAttributionData called")

    local value = SolarEngineSDK.getAttributionData()
    print("getAttributionData raw: " .. tostring(value))

    if not value or value == "" then
        print("⚠️ getAttributionData is empty")
        return
    end

    -- 尝试将 JSON 字符串解析为 Lua table
    local ok, data = pcall(function()
        return json.decode(value)
    end)

    if not ok then
        print("❌ JSON decode failed: " .. tostring(data))
        return
    end

    print("✅ getAttributionData parsed table:")
    dumpTable(data)
end
-- 通用递归打印 table 函数
function dumpTable(t, indent)
    indent = indent or 0
    local prefix = string.rep("  ", indent)
    for k, v in pairs(t) do
        if type(v) == "table" then
            print(prefix .. tostring(k) .. " = {")
            dumpTable(v, indent + 1)
            print(prefix .. "}")
        else
            print(prefix .. tostring(k) .. " = " .. tostring(v))
        end
    end
end
function sedemo.setSuper()
    print("setSuper called")
    local properties = {
        key = "value",
        key2 = "value2",
        key3 = 1,
        key4 = true

    }

    SolarEngineSDK.setSuperProperties({
        test_key = "test_value"
    })
end
function sedemo.unsetSuper()
    print("unsetSuper called")
    SolarEngineSDK.unsetSuperProperty("test_key")
end
function sedemo.clearSuper()
    print("clearSuper called")
    SolarEngineSDK.clearSuperProperties()
end
function sedemo.getPresetProperties()
    print("getSuperProperties called")
    local properties = SolarEngineSDK.getPresetProperties()
    print("properties:" .. properties)
end
function sedemo.userInit()
    print("userInit called")
    SolarEngineSDK.userInit({
        nickname = "Player123",
        age = 25,
        country = "US",
        favorite_genre = "action"
    })

end
function sedemo.userUpdate()
    print("userUpdate called")
    SolarEngineSDK.userUpdate({
        highest_level = 10,
        total_score = 50000,
        age = 30
    })

end
function sedemo.userAdd()
    print("userAdd called")
    SolarEngineSDK.userAdd({
        total_play_time = 1800,
        total_score = 5000,
        coins_earned = 200,
        levels_completed = 2,
        achievements_unlocked = 1
    })
end
function sedemo.userUnset()
    print("userUnset called")
    SolarEngineSDK.userUnset({
        "nickname",
        "age",
        "favorite_genre"
    })

end
function sedemo.userDelete()
    print("userDelete called")
    SolarEngineSDK.userDelete(SolarEngineSDK.userDeleteType.byAccountId)
    SolarEngineSDK.userDelete(SolarEngineSDK.userDeleteType.byVisitorId)

end
function sedemo.userAppend()
    print("userAppend called")
    SolarEngineSDK.userAppend({
        total_play_time = 1000,
        total_score = 3000
    })

end
function sedemo.trackAdImp()
    print("trackAdImp called")

    SolarEngineSDK.trackAdImpression({
        adPlatform = "csj",
        mediationPlatform = "topon",
        adType = 1,
        adAppId = "test_csj_app_id",
        adId = "test_csj_placement_id",
        adECPM = 1.99,
        currencyType = "CNY",
        isRendered = true,
        customProperties = {
            one = "1",
        }
    })
end

function sedemo.trackAdClick()
    print("trackAdClick called")

    SolarEngineSDK.trackAdClick({
        adNetworkPlatform = "csj",
        adType = 1,
        adNetworkPlacementId = "test_csj_placement_id",
        mediationPlatform = "custom",
        customProperties = {
            one = "1",
        } })
end

function sedemo.trackAtt()
    print("trackAtt called")

    SolarEngineSDK.trackAppAttr({
        adNetwork = "google",
        subChannel = "paid",
        adAccountId = "123-456-7890",
        adAccountName = "Game_Marketing_Account",
        adCampaignId = "987654321",
        adCampaignName = "Global_App_Install_Campaign",
        adOfferId = "offer_google_123",
        adOfferName = "Google Play Install",
        adCreativeId = "creative_google_456",
        adCreativeName = "Google_Play_Banner",
        attributionPlatform = "solar_engine",
        customProperties = {
            install_source = "google_ads",
            platform = "android",
            language = "en"
        }
    })

end

function sedemo.trackOrder()
    print("trackOrder called")
    SolarEngineSDK.trackOrder({
        orderId = "order_game_" .. tostring(os.time()),
        payAmount = 29.99,
        currencyType = "USD",
        payType = "ApplePay",
        status = "completed",
        customProperties = {
            product_type = "premium_package",
            order_category = "in_game_purchase",
            items_count = 3
        }
    })

end

function sedemo.trackLogin()
    SolarEngineSDK.trackLogin({
        loginType = "QQ",
        loginStatus = "success",
        customProperties = {
            source = "manual_login"
        }
    })

end

function sedemo.trackRegister()
    SolarEngineSDK.trackRegister({
        registerType = "QQ",
        registerStatus = "success",
        customProperties = {
            source = "game_invitation",
            invite_code = "ABC123",
            referrer_id = "user_789"
        }
    })

end

function sedemo.trackPurchase()
    print("trackPurchase called")

    SolarEngineSDK.trackPurchase({
        productId = "com.game.coin100",
        productName = "100金币包",
        productCount = 1,
        orderId = "orderId",
        payAmount = 1.99,
        currencyType = "USD",
        payType = "ApplePay",
        payStatus = 1,
        failReason = "failReason",
        customProperties = {
            one = "1",
        }
    })
end
function sedemo.appEngagement()
    print("appEngagement called")
    local customProperties = {

        one = "1",
    }
    SolarEngineSDK.trackAppReEngagement(customProperties);
end
function sedemo.trackFirst()
    print("trackFirst called")

    SolarEngineSDK.trackFirstEvent("_appReg", "test_uniqueId", {
        registerType = "QQ",
        registerStatus = "success",
        customProperties = {
            test_key = "test"
        }
    })
    SolarEngineSDK.trackFirstEvent("test_name", "test_uniqueId", {
        test_key = "test"
    })
end
function sedemo.eventStart()
    print("eventStart called")
    SolarEngineSDK.eventStart("game_session")
end
function sedemo.eventFinish()
    print("eventFinish called")
    SolarEngineSDK.eventFinish("game_session", {
        level_reached = 5,
        score = 1500,
        game_mode = "adventure",
        difficulty = "normal",
        coins_earned = 50,
        powerups_used = 2,
        completed_objective = true
    })
end

function sedemo.rcDefaultConfig()
    print("rcDefaultConfig called")
    local list = { 1, 2, 3 }
    local defaultConfig6 = { name = "test", age = 1, list = list }

    local items = {
        SolarEngineSDK.stringItem("test", "teststring"),
        SolarEngineSDK.jsonItem("testjson", defaultConfig6),
        SolarEngineSDK.boolItem("testbool", true),
        SolarEngineSDK.intItem("testint", 1)
    }
    local itemstr = json.encode(items)
    print("itemstr:" .. itemstr)

    SolarEngineSDK.setRemoteDefaultConfig(items)

end
function sedemo.setRemoteConfigEvent()
    print("setRemoteConfigEvent called")
    local properties = {
        rcevent = "event",
    }
    SolarEngineSDK.setRemoteConfigEventProperties(properties)
end
function sedemo.setRemoteConfigUser()
    print("setRemoteConfigUser called")
    local properties = {
        rcuser = "user",
    }
    SolarEngineSDK.setRemoteConfigUserProperties(properties)
end

function sedemo.fastFetchRC()
    print("fastFetchRemoteConfig called")

    local value = SolarEngineSDK.fastFetchRemoteConfig("test")
    print("string:" .. value)
    local value2 = SolarEngineSDK.fastFetchRemoteConfig("testjson")
    print("json:" .. value2)
    local value3 = SolarEngineSDK.fastFetchRemoteConfig("testbool")
    print("bool:" .. value3)
    local value4 = SolarEngineSDK.fastFetchRemoteConfig("testint")
    print("int:" .. value4)

end
function sedemo.fastAllFetchRC()
    print("fastAllFetchRemoteConfig called")
    local value = SolarEngineSDK.fastAllFetchRemoteConfig()
    print("all:" .. value)
end
function sedemo.asyncFetchRC()
    print("asyncFetchRemoteConfig called")
    SolarEngineSDK.asyncFetchRemoteConfig("test", function(result)
        print("asyncresult:" .. result)
        SolarEngineSDK.asyncFetchRemoteConfig("testjson", function(result)
            print("asyncresult:" .. result)
        end)
        SolarEngineSDK.asyncFetchRemoteConfig("testbool", function(result)
            print("asyncresult:" .. result)
        end)
        SolarEngineSDK.asyncFetchRemoteConfig("testint", function(result)
            print("asyncresult:" .. result)
        end)
    end)
end
function sedemo.asyncAllFetchRC()
    print("asyncAllFetchRemoteConfig called")
    SolarEngineSDK.asyncAllFetchRemoteConfig(function(result)
        print("asyncAll:" .. result)
    end)
end

return sedemo
