#!/usr/bin/env python3
import json
import subprocess
import os
import argparse
from argparse import RawTextHelpFormatter
from logger_slg import init_logger
import datetime
from slg_utilities import FileOperations
import time


def get_arguments():
    parser = argparse.ArgumentParser(description='', formatter_class=RawTextHelpFormatter)

    # argument groups can have their tickers combined (ie -su)
    bools = parser.add_argument_group()

    parser.add_argument('-o', '--output_filepath', default='/var/log/slg/time_log.json',
                        help='Where we should log the times')

    args = parser.parse_args()

    return args


if __name__ == '__main__':
    try:
        logger = init_logger(
            name=__name__,
            log_path=f'/var/log/slg/{__file__.split("/")[-1]}.log'
        )
        args = get_arguments()
        print(args)
        abs_file_location = args.output_filepath

        fo = FileOperations(working_directory='/'.join(abs_file_location.split('/')[:-1]), default_filename=abs_file_location.split('/')[-1])

        while True:
            idle_time = int(subprocess.check_output(f"xprintidle", shell=True).strip().decode('utf-8'))
            if idle_time > 10000:
                time.sleep(1)
                output = 'Idle'
            else:
                output = subprocess.check_output(f"xdotool getwindowfocus getwindowname", shell=True).strip().decode('utf-8')

            dt = datetime.datetime.now()
            date = dt.strftime('%Y-%m-%d')
            time_ = dt.strftime('%H:%M:%S')

            print(output)

            try:
                json_obj = fo.read_json()
            except:
                json_obj = {}

            if date not in json_obj:
                json_obj[date] = {}

            json_obj[date][time_] = output

            fo.write_json(json_obj)
            time.sleep(1)

    except:
        logger.exception('An error occurred')
