# -*- coding: utf-8 -*-
""" Created by Safa Arıman on 1/18/20 """
from pisi.db import packagedb, componentdb, sourcedb, repodb
import json

__author__ = 'safaariman'


build_requirements = {}


def build_rev_dep_list(packages, level=0):
    if not packages:
        return None
    for package in packages:
        if package in build_requirements and build_requirements.get(package) < level:
            return None
        if level != 0:
            runtime_deps = packagedb.PackageDB().get_package(package).buildDependencies
            for runtime_dep in runtime_deps:
                build_requirements.update({runtime_dep.name(): level - 1})
        build_requirements.update({package: level})
        reverse_deps = packagedb.PackageDB().get_rev_deps(package)
        build_rev_dep_list([reverse_dep[0] for reverse_dep in reverse_deps], level + 1)


if __name__ == '__main__':
    sources = sourcedb.SourceDB().list_sources('core-source')
    packages = set()
    for source in sources:
        spec = sourcedb.SourceDB().get_spec(source, 'core-source')
        for package in spec.packages:
            packages.add(package.name)
    # build_rev_dep_list(componentdb.ComponentDB().get_packages('programming.library'))
    build_rev_dep_list(list(packages))
    asdasd = set()
    reqs = {}
    for key, value in build_requirements.items():
        try:
            source_name = packagedb.PackageDB().get_package(key).source.name
            if source_name not in asdasd:
                asdasd.add(source_name)
                r_list = reqs.get(value, [])
                r_list.append(source_name)
                reqs.update({value: r_list})
        except Exception as e:
            print(e.message)
    print(json.dumps(reqs))
