CheckStoneFu = AceLibrary("AceAddon-2.0"):new("FuBarPlugin-2.0", "AceConsole-2.0", "AceDB-2.0", "AceEvent-2.0", "AceHook-2.1")
-- variables
local L = AceLibrary("AceLocale-2.2"):new("CheckStoneFu")
local tablet = AceLibrary:HasInstance("Tablet-2.0") and AceLibrary("Tablet-2.0")
local dewdrop = AceLibrary("Dewdrop-2.0")

CheckStoneFu.hasIcon = "Interface\\AddOns\\" .. CheckStoneFu.folderName .. "\\icon"
CheckStoneFu.defaultPosition = "LEFT"

CheckStoneFu:RegisterDB("CheckStoneFuDB")
local options = {
    type='group',
    args = {
		show_high = {
			type = "toggle",
			name = L["Show high time"],
			desc = L["Show high time in FuBar text"],
			get = function() return CheckStoneFu.db.profile.showHigh end,
			set = function()
				CheckStoneFu.db.profile.showHigh = not CheckStoneFu.db.profile.showHigh
				CheckStoneFu:Update()
			end,
		},
		show_low = {
			type = "toggle",
			name = L["Show low time"],
			desc = L["Show low time in FuBar text"],
			get = function() return CheckStoneFu.db.profile.showLow end,
			set = function()
				CheckStoneFu.db.profile.showLow = not CheckStoneFu.db.profile.showLow
				CheckStoneFu:Update()
			end,
		},

	}
}
CheckStoneFu:RegisterChatCommand({"/csfu"}, options)


	-- Methods
function CheckStoneFu:IsShowingHigh()
	return self.db.profile.showHigh
end

function CheckStoneFu:ToggleShowingHigh()
	self.db.profile.showHigh = not self.db.profile.showHigh
	self:Update()
	return self.db.profile.showHigh
end

function CheckStoneFu:IsShowingLow()
	return self.db.profile.showLow
end

function CheckStoneFu:ToggleShowingLow()
	self.db.profile.showLow = not self.db.profile.showLow
	self:Update()
	return self.db.profile.showLow
end

function CheckStoneFu:OnInitialize()
		self.BUFF_SEARCH_STRING = "Soulstone Resurrection"
end

function CheckStoneFu:OnEnable()
	self.members = {}
	self.current_high = 0
	self.current_low = 999999999999
	self.CHKSTONE_TOTAL_STONED = 0
	self.INRAID = 0;
	self.INGROUP = 0;
	self.initialscan = 1;
	self:ScheduleRepeatingEvent("UpdateSelf",self.Update,1,self);
end

function CheckStoneFu:OnMenuRequest(level, value, inTooltip)
	if level == 1 then
		dewdrop:AddLine(
			'text', L["Show high time"],
			'arg1', self,
			'func', "ToggleShowingHigh",
			'checked', self:IsShowingHigh(),
			'closeWhenClicked', false
		)
		dewdrop:AddLine(
			'text', L["Show low time"],
			'arg1', self,
			'func', "ToggleShowingLow",
			'checked', self:IsShowingLow(),
			'closeWhenClicked', false
		)
	end
end

function CheckStoneFu:OnDataUpdate()
	local numraid = GetNumRaidMembers()
	local numparty = GetNumPartyMembers()
	self.current_high = 0
	self.current_low = 999999999999
	self.CHKSTONE_TOTAL_STONED = 0
	if(numraid > 1) then
		self.INRAID = 1;
		self.INGROUP = 0;
	elseif(numparty > 1) then
		if(self.INRAID == 1) then
			self.members = {};
		end
		self.INRAID = 0;
		self.INGROUP = 1;
	else
		if(self.INRAID == 1 or self.INGROUP == 1) then
			self.members = {};
		end
		self.INRAID = 0;
		self.INGROUP = 0;
	end
	if(self.INRAID == 1) then
		for i=1, numraid do
			local member_unit = "raid"..i;
			self:check_status(member_unit);
		end
	else
		if(self.INGROUP == 1) then
			for i=1, numparty do
				local member_unit = "party"..i;
				self:check_status(member_unit);
			end
		end
		self:check_status("player");
	end
	self.initialscan = 0;
end

function CheckStoneFu:check_status(unit)
	local buff_found = CheckStoneFu:check_buff_present(unit);
	if(members == nil) then
		members = {};
	end
	if(UnitName(unit) ~= nil) then
		if(buff_found == 1) then
			--SendChatMessage("A buff was found", "CHANNEL", nil, 4)
			if(members[UnitName(unit)] == nil) then
				if(self.initialscan == 0) then
					members[UnitName(unit)] = time();
				else
					members[UnitName(unit)] = -1;
				end
			else
				if(members[UnitName(unit)] == 0) then
					if(self.initialscan == 0) then
						members[UnitName(unit)] = time();
					else
						members[UnitName(unit)] = -1;
					end
				end
			end
		else
			if(members[UnitName(unit)] == nil) then
				members[UnitName(unit)] = 0;
			elseif(members[UnitName(unit)] ~= 0) then
				CheckStoneFu:announce_lost_buff(unit);
				members[UnitName(unit)] = 0;
			end
		end
	end
		if(members[UnitName(unit)] > 0 or members[UnitName(unit)] == -1) then
			self.CHKSTONE_TOTAL_STONED = self.CHKSTONE_TOTAL_STONED + 1;
		end
		if((time() - members[UnitName(unit)]) > self.current_high) then
			self.current_high = members[UnitName(unit)];
		end
		if((time() - members[UnitName(unit)]) < self.current_low) then
			self.current_low = members[UnitName(unit)];
		end
end

function CheckStoneFu:announce_lost_buff(unit)
	if(DEFAULT_CHAT_FRAME) then
		DEFAULT_CHAT_FRAME:AddMessage("*** "..UnitName(unit).." has lost their SOULSTONE! ***", 1, 1, 1, 1, 5)
	end
	if(CT_RAMessageFrame) then
		CT_RAMessageFrame:AddMessage("*** "..UnitName(unit).." has lost their SOULSTONE! ***", 1, 1, 1, 1, 5)
	end
end
		
function CheckStoneFu:check_buff_present(unit)
	local buff_found = 0
	local buff_ittr = 1
	while (UnitBuff(unit, buff_ittr)) do
		if (string.find(UnitBuff(unit,buff_ittr), self.BUFF_SEARCH_STRING)) then
			buff_found = 1			
		end
			buff_ittr = buff_ittr + 1
		end
  return buff_found
end

function CheckStoneFu:OnTextUpdate()
	local current_string = "";
	current_string = "Soulstones: "..self.CHKSTONE_TOTAL_STONED;
	if(self.current_high ~= 0) then
		if(self:IsShowingHigh()) then
			local high_minutes = CheckStoneFu:calculate_time_left(self.current_high);
			current_string = current_string .. " High: "..high_minutes;
		end
		if(self:IsShowingLow()) then
			local low_minutes = CheckStoneFu:calculate_time_left(self.current_low);
			current_string = current_string .. " Low: "..low_minutes;
		end
	end
	self:SetText(current_string);
end

function CheckStoneFu:OnTooltipUpdate()
	local cat = tablet:AddCategory('columns', 2, 'child_textR', 0, 'child_textG', 1, 'child_textB', 0)
	local lines_added = false
	for k in pairs(members) do
		if(members[k] ~= 0) then
			if(members[k] == -1) then
				cat:AddLine('text',k..": ",'text2', "UNKNOWN");
			else
				cat:AddLine('text',k..": ",'text2', CheckStoneFu:calculate_time_left(members[k]));
			end
			lines_added = true;
		end
	end		
	if lines_added == false then
		cat:AddLine('text', L["NO SOULSTONES"])
	end
end

function CheckStoneFu:calculate_time_left(recorded_time)
	local elapsed_seconds = time() - recorded_time
	local total_seconds = 1800 - elapsed_seconds
	local leftover_seconds = mod(total_seconds,60)
	local total_minutes = (total_seconds - leftover_seconds) / 60
	local seconds_string = ""
	local minutes_string = ""
	if(recorded_time == -1) then
		return "UNKNOWN";
	end
	if(leftover_seconds < 10) then
		seconds_string = "0"..leftover_seconds
	else
		seconds_string = leftover_seconds
	end
	if(total_minutes == 0) then
		minutes_string = "00"
	else
		minutes_string = total_minutes
	end
  return minutes_string..":"..seconds_string
end
