#!/usr/bin/env python3

from __future__ import print_function
import sys
sys.path.append('/usr/share/botch')
from util import get_fh_out, sort_pkgs_key, read_tag_file


def packages_difference(inPackages1, inPackages2, outPackages, verbose=False):
    to_remove = dict()

    for pkg in inPackages2:
        to_remove[(pkg['Package'], pkg['Architecture'], pkg['Version'])] = pkg

    result = dict()

    nr_removed = 0
    nr_all = 0
    for pkg in inPackages1:
        nr_all += 1
        name, arch, ver = pkg['Package'], pkg['Architecture'], pkg['Version']
        if not to_remove.get((name, arch, ver)):
            result[(name, arch, ver)] = pkg
        else:
            nr_removed += 1

    with outPackages as outfile:
        for pkg in sorted(list(result.keys()), key=sort_pkgs_key):
            result[pkg].dump(outfile)
            outfile.write(b"\n")

    if verbose:
        print("Removed %d out of %d packages" %
              (nr_removed, nr_all), file=sys.stderr)

    return True

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(
        description=("calculate the difference of two packages files, " +
                     "removing from the first packages file all packages " +
                     "that are in the second file"))
    parser.add_argument(
        'inPackages1', type=read_tag_file, help='input Packages file #1')
    parser.add_argument(
        'inPackages2', type=read_tag_file, help='input Packages file #2')
    parser.add_argument(
        'outPackages', type=get_fh_out, help='output Packages file')
    parser.add_argument('--verbose', action='store_true', help='be verbose')
    args = parser.parse_args()
    ret = packages_difference(
        args.inPackages1, args.inPackages2, args.outPackages, args.verbose)
    exit(not ret)
