#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys, os, time, subprocess, signal
import gi
from gi.repository import GLib

TMP_FILE = "/tmp/wf_rec_waybar"

def get_time(s_time):
	n_time = time.time()
	return time.strftime("%H:%M:%S",time.gmtime(n_time - float(s_time)))

def finish_record():
	os.system("killall -s SIGINT wf-recorder")
	os.system("rm {}".format(TMP_FILE))

def get_record_area():
	global ss_size
	ss_size = subprocess.Popen(["slurp"], stdout = subprocess.PIPE)
	ss_size.wait()
	ss_size = ss_size.communicate()[0]
	ss_size = ss_size.decode("utf-8","strict")
	ss_size = ss_size.replace("\n","")
	return ss_size
	

def open_tmp_file_start_record(ss_size):
	directory = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_VIDEOS)
	if directory == None:
		directory = os.path.expanduser("~")
	directory = os.path.join(directory,time.strftime("%F_%H%M%S.mp4",time.localtime(time.time())))
	if ss_size:
		get = subprocess.Popen(["sh","-c",'wf-recorder -g "{}" -a -f "{}"'.format(ss_size,directory)])
	else:
		get = subprocess.Popen(["sh","-c",'wf-recorder -a -f "{}"'.format(directory)])
	f = open(TMP_FILE,"w")
	s_time = str(time.time())
	f.write("{}\n{}".format(s_time,directory))
	f.close()

def read_tmp_file():
	"""File Format
	start_time
	directory"""
	f = open(TMP_FILE,"r")
	read_data = f.readlines()
	f.close()
	return read_data
		

if __name__ == '__main__':
	args = sys.argv
	if os.path.exists(TMP_FILE):
		read_data = read_tmp_file()
	else:
		read_data = False
	if "--click" in args or "--middle" in args:
		if read_data:
			finish_record()
		else:
			ss_size = False
			if "--middle" in args:
				ss_size = get_record_area()
			open_tmp_file_start_record(ss_size)
	else:
		if read_data:
			print("<span color=\"#fa2772\"> {}</span>".format(get_time(read_data[0][:-1])))
		else:
			print("")
