--[[
This is an example script for the lua engine in TailExpert

]]--
require('Config')

-- Import WIndows Assemblies
import('System.Windows.Forms')
import('System.Drawing')
import('System.Drawing.Drawing2D')
import('GraphLib') 

--[[
local form = Form()
form.Height = 600
form.Width = 800
form.Text = "Output window of GraphExample.lua"
form.HelpButton=false
form.MaximizeBox=true
form.MinimizeBox=true
]]--

local display = PlotterGraphEx()
display.Dock = DockStyle.Fill
local dataSource = DataSource()

function AddNumberToGraph(ds, idx, value)
	if idx < ds.Length then
        local point=cPoint(idx,value)
        point.x = idx
        point.y = value
        ds.Samples:SetValue(point, idx)
	end
end

function RenderYLabel(ds, idx)
	return string.format("%.2f", idx)
end

function RenderXLabel(ds, idx)
	return string.format("%.2f", ds.Samples:GetValue(idx).x)
end


display.DoubleBuffering=true
display.DataSources:Clear()
display:SetDisplayRangeX(0, 200)
display:SetGridDistanceX(20)
display:SetGridOriginX(0)
display.Smoothing = HighSpeed;

display.DataSources:Add(dataSource)
display.DataSources[0].Name = "CPU Temperature"                
  
display.DataSources[0].Length = 1000
display.PanelLayout = PlotterGraphPaneEx.LayoutMode.NORMAL
display.DataSources[0].AutoScaleX = false
display.DataSources[0].AutoScaleY = false
display.DataSources[0]:SetDisplayRangeY(0, 100)
display.DataSources[0]:SetGridDistanceY(10)
--display.DataSources[0].OnRenderYAxisLabel = RenderYLabel
display.DataSources[0].OnRenderXAxisLabel = RenderXLabel



--form.Controls:Add(display)
--form:Show()
--display:Show() 

--[[
Script starts here
]]--

local filename = 'c:\\temp\\wfdlog.log'
local file = nill

function MakeLogMessage(module,severity,message)
    local line
    local dd = GetDateTimeString("yyyy-MM-dd HH:mm:ss:fff")
    line = dd .. " " .. severity .. " " .. message
    return line
end

function CreateLog(file)
    local message
    for i=1,1000,1 do
        local temp = 48.0 + math.random()*10.0
        message = MakeLogMessage("TEST", "INFO", "Temperature = " .. temp .. " C\n")
        file:write(message)
    end
    file:flush()
end

local linenr = 1
local lines = {}
function ReadFile(f)
	-- Do not put message here as it will make a recurring effect when you have log enabled and load MultiTail.log
	if ScriptInitialized == true then
		if feof(f) ~= nill then
			while feof(f) ~= true do
				local line = f:read("*line")
				if line ~= nill then
					local f = string.match(line, "Temperature = %d+%.%d+") 
					if f ~= nill then
						local value = string.match(f, "%d+%.%d+")
						if (value ~= nill) then
							--LogMessage(INFO, linenr .. " " .. value)
							AddNumberToGraph(display.DataSources[0], linenr, tonumber(value))
							linenr = linenr + 1
						end
					end
					table.insert(outputBuffer, line)
				end
			end
			display:Refresh()
			SelectTab('Custom[GraphExample]')
		end
	end
end

--[[
Required predefined functions: Are called from TailExpert, adapt to your needs
]]--

function OnEvaluate(loglines)
    -- Do not put LogMessage() here this will overflow your logs as
    -- Evaluate is called every tail cycle
    -- If you need log make sure it's not output every cycle
	if ScriptInitialized == true then 
		ReadFile(file)
		PutLogLines(outputBuffer) 
	end
end

function OnEnter()
	ScriptInitialized = true
	LogMessage(INFO, "GraphExample.lua script OnEnter()")

    -- tests the functions above
    if file_exists(filename) then
        file = assert(io.open(filename, "w+"))  -- changed from a+ append
    else
        file = assert(io.open(filename, "w+"))
    end
	local tab = OpenCustomTab("GraphExample", false)
	tab._mLogPanel.Controls:Add(display)
	
	display:Show()
    CreateLog(file)
    file:seek("set", 0)
 	ScriptInitialized = true
end

function OnExit()
	LogMessage(INFO, "GraphExample.lua script OnExit()")
	ScriptInitialized = false
	CloseTab('Custom[GraphExample]')
	file:close()
end
