#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2023 Sandro Knauß <hefee@debian.org>
# SPDX-License-Identifier: LGPL-2.0-or-later

import logging
import pathlib

from debian import deb822

logging.basicConfig(format='%(levelname).1s: pkgkde '
                           '%(module)s:%(lineno)d: %(message)s')
log = logging.getLogger('pkgkde')

PATHS = [pathlib.Path(__file__).parent.with_name("datalib"),
         pathlib.Path('/usr/share/pkg-kde-tools/lib')
        ]

class DebianControl:
    """ Simple class for debian/control file.

    source: with point to the source entry in contrile file
    packages: dict with all binary packages in control file

    """
    def __init__(self, path: pathlib.Path) -> None:
        self.path = path

        self.read_path(path)

    def read_path(self, path:pathlib.Path) -> None:
        self.source = None
        self.packages = {}
        with path.open() as cl:
            for block in deb822.Deb822.iter_paragraphs(cl):
                if block.get("Source"):
                    self.source = block
                else:
                    self.packages[block.get("Package")] = block

    def isSinglePackage(self) -> bool:
        """Is there only one binary package?"""
        return len(self.packages) == 1


def set_substvar(path:pathlib.Path, substvars: dict):
    """ handles a debian/substvars file.

        path: path to substvars file.
        substsvars: is a dict to set key,value in the substvars file.
    """
    data = ''
    if path.exists():
        data = path.read_text()

    for name, values in substvars.items():
        p = data.find(f"{name}=")
        items = set()
        if p > -1:
            e = data[p:].find('\n')
            line = data[p + len(f"{name}="):p + e if e > -1 else None]
            items = set(i.strip() for i in line.split(',') if i)
        else:
            p = len(data)
            e = -1

        if values - items:
            items |= values

            new_line = ",".join(sorted(items))
            start = data[:p]
            end = ""
            if e > -1:
                end = data[p + e:]

            data = start

            if data:
                data += "\n"

            data += f"{name}={new_line}\n"

            if end.strip():
                data += end

    data = data.replace('\n\n', '\n')
    if data:
        path.write_text(data)
