summaryrefslogtreecommitdiffstatshomepage
path: root/plugins/timer/init.lua
blob: 3b00bb01f9b584a8431eb6aca238432328101e43 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
-- license:BSD-3-Clause
-- copyright-holders:Carl
require('lfs')
local exports = {}
exports.name = "timer"
exports.version = "0.0.1"
exports.description = "Game play timer"
exports.license = "The BSD 3-Clause License"
exports.author = { name = "Carl" }

local timer = exports

function timer.startplugin()
	local timer_path = "timer"
	local timer_started = false
	local total_time = 0
	local start_time = 0
	local play_count = 0

	local function get_filename()
		local path
		if emu.softname() ~= "" then
			path = timer_path .. '/' .. emu.romname() .. "_" .. emu.softname() .. ".time"
		else
			path = timer_path .. '/' .. emu.romname() .. ".time"
		end
		return path
	end

	local function save()
		total_time = total_time + (os.time() - start_time)
		os.remove(get_filename()) -- truncate file
		file = io.open(get_filename(), "w")
		if not file then
			lfs.mkdir(timer_path)
			file = io.open(get_filename(), "w")
		end
		if file then
			file:write(total_time .. "\n")
			file:write(play_count)
			file:close()
		end
	end


	emu.register_start(function()
		local file
		if timer_started then
			save()
		end
		timer_started = true
		local file = io.open(get_filename(), "r")
		if file then
			total_time = file:read("n")
			play_count = file:read("n")
			file:close()
		end
		start_time = os.time()
		play_count = play_count + 1
	end)

	emu.register_stop(function() 
		timer_started = false
		save()
		total_time = 0
		play_count = 0
	end)

	local function sectohms(time)
		local hrs = math.floor(time / 3600)
		local min = math.floor((time % 3600) / 60)
		local sec = time % 60
		return string.format("%03d:%02d:%02d", hrs, min, sec)
	end

	local function menu_populate()
		local time = os.time() - start_time
		return {{ "Current time", "", 32 },
			{ sectohms(time), "", 32 },
			{ "Total time", "", 32 },
			{ sectohms(total_time + time), "", 32 },
			{ "Play Count", "", 32 },
			{ play_count, "", 32 }}
	end

	local function menu_callback(index, event)
		return true
	end

	emu.register_menu(menu_callback, menu_populate, "Timer")
end

return exports