#!/usr/bin/python3

import time
import configparser
from pathlib import Path
import subprocess

import pyinotify

from pmenu.conf import Conf


class UserConf:
    last_app = None
    nb_launched = 0

    def __init__(self, server_conf):
        config_path = f'{Path.home()}/.config/primtuxmenu/primtuxmenu.conf'
        self.config_path = Path(config_path)
        self.config_path.parent.mkdir(exist_ok=True, parents=True)
        Path(config_path).touch()

        self.server_conf = server_conf
        self._clear()

    def _get_conf(self):
        config = configparser.RawConfigParser()
        config.read(self.config_path)
        if config.has_option('DEFAULT', 'lastApp'):
            self.last_app = config.get('DEFAULT', 'lastApp')
        if config.has_option('DEFAULT', 'nblaunched'):
            self.nb_launched = int(config.get('DEFAULT', 'nblaunched').strip())

    def _clear(self):
        self.server_conf.last_app = ''
        self.server_conf.nb_launched = 0
        try:
            self.server_conf.update()
        except PermissionError:
            pass
        self.last_app = ''
        self.update()

    def is_new(self):
        self._get_conf()
        self.server_conf.get()

        print('last launched :', self.last_app, self.server_conf.last_app)
        print(
			'nb launched :',
			self.nb_launched,
			self.server_conf.nb_launched
		)
        if (
			self.last_app == self.server_conf.last_app
            and self.nb_launched == self.server_conf.nb_launched
        ):
            return False
        self.last_app = self.server_conf.last_app
        self.nb_launched = self.server_conf.nb_launched
        return True

    def get(self):
        return self.last_app

    def update(self):
        config = configparser.ConfigParser()
        if not self.last_app:
            return
        config.set('DEFAULT', 'lastapp', self.last_app)
        config.set('DEFAULT', 'nblaunched', str(self.nb_launched))
        with open(self.config_path, 'w') as configfile:
            config.write(configfile)
        print('config updated for :', configfile)


def run(cmd):
    print(cmd)
    if not cmd:
        return
    try:
        subprocess.Popen(
            cmd.split(' '),
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            close_fds=True
        )
    except:
        return


class PrimtuxMenUserEventHandler(pyinotify.ProcessEvent):
    def __init__(self, user_conf):
        self.user_conf = user_conf

    def process_IN_CREATE(self, event):
        self._update_apps()

    def process_IN_CLOSE_WRITE(self, event):
        self._update_apps()

    def process_IN_DELETE(self, event):
        self._update_apps()

    def _update_apps(self):
        if self.user_conf.is_new():
            cmd = self.user_conf.get()
            run(cmd)
            self.user_conf.update()


if __name__ == "__main__":
    server_conf = Conf()
    user_conf = UserConf(server_conf)
    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(
        wm,
        PrimtuxMenUserEventHandler(user_conf)
    )

    wm.add_watch(
        server_conf.dynamic_conf,
        pyinotify.IN_CREATE
        | pyinotify.IN_DELETE
        | pyinotify.IN_CLOSE_WRITE
    )
    notifier.loop()
