#!/usr/bin/env python3

""" Produce a list plugin builds per platform

Typical use:

$ ./plugin-coverage ../ocpn-plugins.xml > coverage.csv

OpenOffice calc post processing:

Import csv file to calc, File | Open or xdg-open

Format | Page | Landscape mode
Select header row, exclude name at start and end
Format | Cells, adjust angle to 90°.
Format | Columns, set width to 0.5 cm
Format | Print Ranges | Edit, set Rows To Repeat to User Defined, $1
Export as PDF...


"""

#./plugin-by-author \
#     ../ocpn-plugins.xml  | sort | uniq | sed 's|https://github.com/||g'

import hashlib
import os
import sys
import tempfile
import xml.etree.ElementTree as ET



def get_build_key(tree):
    key = tree.find('./target').text.strip() 
    return key + ":" + tree.find('./target-version').text.strip()

def get_name(tree):
    return tree.find('./name').text.strip()

def main():
    """Check urls in sys.argv[], defaults to ocpn-plugins.xml."""
    if len(sys.argv) == 0:
        sys.argv.extend(["ocpn-plugins.xml"])
    sys.argv = sys.argv[1:]
    names = set()
    builds_by_name = {}
    plugins = []
    all_keys = set()
    for path in sys.argv:
        tree = ET.parse(path)
        if tree.getroot().tag == 'plugin':
            plugins = [tree]
        else:
            plugins = tree.findall('./plugin')
        names = names.union({p.find('./name').text.strip() for p in plugins })
    for name in names:
        keys = [get_build_key(p) for p in plugins if get_name(p) == name ]
        builds_by_name = builds_by_name | {name: keys}
        all_keys = all_keys | set(keys)
    count_by_key = {}
    for key in all_keys:
        count = 0
        for name in names:
            if key in builds_by_name[name]: count += 1
        count_by_key[key] = count
    all_keys = sorted(all_keys, key = lambda k: -count_by_key[k])

    print("name," +  ",".join(all_keys))
    for name in sorted(names):
        print(f'{name[:20]: <22}' + ',', end='')
        x = []
        for key in all_keys:
            x.append('x' if key in  builds_by_name[name] else '-')
        print(','.join(x), end='')
        print("," + name)


if __name__ == '__main__':
    main()
