from setux.core.package import CommonPackager
from setux.targets import Local
from setux.logger import info, error


# pylint: disable=no-member


class Distro(CommonPackager):
    manager = 'flatpak'

    def do_init(self):
        ret, out, err = self.run('flatpak --version')
        if ret==0:
            ret, out, err = self.run(
                'flatpak run com.github.tchx84.Flatseal -h',
                report = 'quiet',
            )
            if ret!=0:
                self.do_install('flatseal')
            return
        self.target.Package.install('flatpak')
        self.run('''
            flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
        ''')
        info(' * REBOOT needed *')

    def do_install(self, pkg, ver=None):
        ret, out, err = self.run(f'flatpak install -y flathub {pkg}')

    def do_installed(self, pattern=None):
        ret, out, err = self.run('flatpak list --columns=application,version')
        for line in out[1:]:
            try:
                n, v  = line.split()
                yield n.strip(), v.strip()
            except: pass

    def do_installable_cache(self):
	# flatpak search --columns=description
        ret, out, err = self.run(
            'flatpak remote-ls flathub',
            report = 'quiet',
        )
        if ret!=0:
            error('\n'.join(out))
            return

        with open(self.cache_file, 'w') as pkg:
            for line in out:
                _desc, app, ver, _inst = line.split('\t')
                if ver.strip():
                    pkg.write(f'{app} {ver}\n')

    def do_remove(self, pkg):
        self.run(f'flatpak uninstall -y {pkg}')

    def do_cleanup(self):
        raise NotImplemented

    def do_update(self):
        raise NotImplemented

