DROP TRIGGER IF EXISTS call_duration_inbound;
CREATE TRIGGER call_duration_inbound AFTER UPDATE OF inbound_gsm ON call_duration FOR EACH ROW WHEN new.inbound_gsm > 0
BEGIN
	update events set end_time = (case when end_time=0 then start_time else end_time end) + ((select new.inbound_gsm) - (select old.inbound_gsm))
	where id = (select id from events where event_type_id = 1 and outgoing = 0 and service_id = 1 and local_uid='ring/tel/ring' order by start_time desc limit 1);
END;


DROP TRIGGER IF EXISTS call_duration_outbound;
CREATE TRIGGER call_duration_outbound AFTER UPDATE OF outbound_gsm ON call_duration FOR EACH ROW WHEN new.outbound_gsm > 0
BEGIN
	update events set end_time = (case when end_time=0 then start_time else end_time end) + ((select new.outbound_gsm) - (select old.outbound_gsm))
	where id = (select id from events where event_type_id = 1 and outgoing = 1 and service_id = 1 and local_uid='ring/tel/ring' order by start_time desc limit 1);
END;


DROP TRIGGER IF EXISTS call_duration_voip_in;
CREATE TRIGGER call_duration_voip_in AFTER UPDATE OF inbound_voip ON call_duration FOR EACH ROW WHEN new.inbound_voip > 0
BEGIN
	update events set end_time = (case when end_time=0 then start_time else end_time end) + ((select new.inbound_voip) - (select old.inbound_voip))
	where id = (select id from events where event_type_id = 1 and outgoing = 0 and service_id = 1 and local_uid!='ring/tel/ring' order by start_time desc limit 1);
END;


DROP TRIGGER IF EXISTS call_duration_voip_out;
CREATE TRIGGER call_duration_voip_out AFTER UPDATE OF outbound_voip ON call_duration FOR EACH ROW WHEN new.outbound_voip > 0
BEGIN
	update events set end_time = (case when end_time=0 then start_time else end_time end) + ((select new.outbound_voip) - (select old.outbound_voip))
	where id = (select id from events where event_type_id = 1 and outgoing = 1 and service_id = 1 and local_uid!='ring/tel/ring' order by start_time desc limit 1);
END;
