local uci = require("uci").cursor()
local fs = require("nixio.fs")

-- 保存流量数据的文件路径
local traffic_file = "/tmp/mytraffic_traffic_data"

-- 获取物理接口名称
function get_physical_interface(logical_interface)
    local iface = uci:get("network", logical_interface, "ifname")
    return iface
end

-- 获取所有网络接口
function get_interfaces()
    local interfaces = {}
    uci:foreach("network", "interface", function(section)
        table.insert(interfaces, section[".name"])
    end)
    return interfaces
end

-- 读取持久化的流量数据
local function read_saved_traffic()
    if fs.access(traffic_file) then
        local data = fs.readfile(traffic_file)
        return data and loadstring("return " .. data)() or {rx_bytes = 0, tx_bytes = 0}
    end
    return {rx_bytes = 0, tx_bytes = 0}
end

-- 保存当前累计的流量数据
local function save_traffic(data)
    fs.writefile(traffic_file, "{" .. string.format("rx_bytes = %d, tx_bytes = %d", data.rx_bytes, data.tx_bytes) .. "}")
end

-- 统计流量并累计（使用物理接口）
function get_traffic(logical_interface)
    if not logical_interface or logical_interface == "" then
        return { rx_bytes = 0, tx_bytes = 0 }
    end

    -- 获取物理接口
    local physical_interface = get_physical_interface(logical_interface)
    if not physical_interface then
        luci.sys.syslog("找不到对应的物理接口：" .. logical_interface)
        return { rx_bytes = 0, tx_bytes = 0 }
    end

    local result = {
        rx_bytes = 0,
        tx_bytes = 0
    }

    local file = io.open("/proc/net/dev", "r")
    if not file then
        luci.sys.syslog("无法打开 /proc/net/dev")
        return result
    end

    for line in file:lines() do
        if line:find(physical_interface .. ":") then
            local rx, tx = line:match(physical_interface .. ":%s*(%d+)%s*%d+%s*%d+%s*%d+%s*%d+%s*%d+%s*%d+%s*(%d+)")
            result.rx_bytes = tonumber(rx) or 0
            result.tx_bytes = tonumber(tx) or 0
            break
        end
    end

    file:close()

    local saved_traffic = read_saved_traffic()

    result.rx_bytes = result.rx_bytes + saved_traffic.rx_bytes
    result.tx_bytes = result.tx_bytes + saved_traffic.tx_bytes

    save_traffic(result)

    return result
end

-- 获取并显示累计流量数据
local m = Map("mytraffic", "流量统计设置")

local config = uci:get_all("mytraffic", "@settings[0]")
local interface = config.interface
local max_traffic = tonumber(config.max_traffic) or 0

-- 获取流量数据（使用物理接口）
local traffic = get_traffic(interface)
local total_traffic = (traffic.rx_bytes + traffic.tx_bytes) / (1024 * 1024 * 1024)  -- 转换为GB

-- 添加显示当前流量和最大流量的部分
m.title = string.format("流量统计 - 已用: %.2f GB / %.2f GB", total_traffic, max_traffic)

local s = m:section(TypedSection, "settings", "设置")
s.addremove = false
s.anonymous = true

local o = s:option(ListValue, "interface", "接口")
for _, iface in ipairs(get_interfaces()) do
    o:value(iface)
end

local o = s:option(Value, "max_traffic", "最大流量 (GB)")
o.datatype = "uinteger"

local o = s:option(Flag, "auto_reset", "每月自动重置")

local o = s:option(Flag, "shutdown", "达到限制时关闭接口")

-- 获取并显示累计流量数据
local received = m:section(TypedSection, "traffic", "接收流量")
received.anonymous = true
received:option(DummyValue, "rx_bytes", "接收字节").value = traffic.rx_bytes

local sent = m:section(TypedSection, "traffic", "发送流量")
sent.anonymous = true
sent:option(DummyValue, "tx_bytes", "发送字节").value = traffic.tx_bytes

return m
