#!/usr/bin/python3

import os
import struct
import select
import ctypes
import configparser
from pathlib import Path
import subprocess

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 :', self.config_path)


def run(cmd):
    print(cmd)
    if not cmd:
        return
    try:
        subprocess.Popen(
            cmd.split(' '),
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            close_fds=True
        )
    except Exception as e:
        print(f"Erreur : {type(e).__name__}: {e}")
        return


def watch_file(filepath, callback):
    IN_MODIFY = 0x00000002
    IN_CLOSE_WRITE = 0x00000008
    IN_CREATE = 0x00000100
    IN_DELETE = 0x00000200
    IN_MOVED_TO = 0x00000080

    libc = ctypes.CDLL('libc.so.6')

    fd = libc.inotify_init()
    if fd < 0:
        raise OSError("Impossible d'initialiser inotify")

    watch_path = Path(filepath)
    watch_dir = watch_path.parent
    target_filename = watch_path.name

    mask = IN_CREATE | IN_DELETE | IN_CLOSE_WRITE | IN_MODIFY | IN_MOVED_TO

    path_bytes = str(watch_dir).encode('utf-8')
    wd = libc.inotify_add_watch(fd, path_bytes, mask)

    if wd < 0:
        os.close(fd)
        raise OSError(f"Impossible de surveiller {watch_dir}")
    print(f"Surveillance de {filepath}...")
    try:
        while True:
            select.select([fd], [], [])
            buf = os.read(fd, 1024)
            i = 0
            event_found = False
            while i < len(buf):
                wd_ev, mask_ev, cookie, length = struct.unpack_from('iIII', buf, i) # noqa
                i += 16
                name = buf[i:i+length].rstrip(b'\x00').decode('utf-8', errors='ignore') # noqa
                i += length
                if name == target_filename:
                    event_found = True
            if event_found:
                callback()
    except KeyboardInterrupt:
        print("\nArrêt...")
    finally:
        os.close(fd)


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


if __name__ == "__main__":
    server_conf = Conf()
    user_conf = UserConf(server_conf)

    watch_file(server_conf.dynamic_conf, on_file_changed)
