#!/usr/bin/python3
#   Copyright (C) 2013 Canonical Ltd.
#
#   Author: Scott Moser <scott.moser@canonical.com>
#
#   Simplestreams is free software: you can redistribute it and/or modify it
#   under the terms of the GNU Affero General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or (at your
#   option) any later version.
#
#   Simplestreams is distributed in the hope that it will be useful, but
#   WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
#   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
#   License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with Simplestreams.  If not, see <http://www.gnu.org/licenses/>.

import argparse
import json
import os
import sys
from simplestreams import util

import toolutil


def tab2items(content):
    # tab content is
    #    content-id product_name version_name img_name [key=value [key=value]]
    # return a list with each item containing:
    #    (content_id, product_name, version_name, item_name, {data})
    items = []
    for line in content.splitlines():
        fields = line.split('\t')
        content_id, prodname, vername, itemname = fields[0:4]

        kvdata = {}
        if len(fields) > 4:
            for field in fields[4:]:
                key, value = field.split("=")
                if key == "size":
                    kvdata[key] = int(value)
                else:
                    kvdata[key] = value

        items.append((content_id, prodname, vername, itemname, kvdata,))

    return items


def items2content_trees(itemslist, exdata):
    # input is a list with each item having:
    #   (content_id, product_name, version_name, item_name, {data})
    ctrees = {}
    for (content_id, prodname, vername, itemname, data) in itemslist:
        if content_id not in ctrees:
            ctrees[content_id] = {'content_id': content_id,
                                  'format': 'products:1.0', 'products': {}}
            ctrees[content_id].update(exdata)

        ctree = ctrees[content_id]
        if prodname not in ctree['products']:
            ctree['products'][prodname] = {'versions': {}}

        prodtree = ctree['products'][prodname]
        if vername not in prodtree['versions']:
            prodtree['versions'][vername] = {'items': {}}

        vertree = prodtree['versions'][vername]

        if itemname in vertree['items']:
            raise ValueError("%s: already existed" %
                             str([content_id, prodname, vername, itemname]))

        vertree['items'][itemname] = data
    return ctrees


def main():
    parser = argparse.ArgumentParser(
        description="create content tree from tab data")

    parser.add_argument("input", metavar='file',
                        help=('source tab delimited data'))

    parser.add_argument("out_d", metavar='out_d',
                        help=('create content under output_dir'))

    parser.add_argument('--sign', action='store_true', default=False,
                        help='sign all generated files')

    args = parser.parse_args()

    if args.input == "-":
        tabinput = sys.stdin.read()
    else:
        with open(args.input, "r") as fp:
            tabinput = fp.read()

    streamdir = "streams/v1"

    items = tab2items(tabinput)
    data = {'updated': util.timestamp(), 'datatype': 'image-downloads'}
    trees = items2content_trees(items, data)

    index = {"index": {}, 'format': 'index:1.0',
             'updated': data['updated']}

    to_write = [("%s/%s" % (streamdir, 'index.json'), index,)]

    not_copied_up = ['content_id']
    for content_id in trees:
        util.products_condense(trees[content_id])
        content = trees[content_id]
        index['index'][content_id] = { 
            'path': "%s/%s.json" % (streamdir, content_id),
            'products': list(content['products'].keys()),
        }
        for k in util.stringitems(content):
            if k not in not_copied_up:
                index['index'][content_id][k] = content[k]

        to_write.append((index['index'][content_id]['path'], content,))

    for (outfile, data) in to_write:
        filef = os.path.join(args.out_d, outfile)
        util.mkdir_p(os.path.dirname(filef))
        with open(filef, "w") as fp:
            sys.stderr.write("writing %s\n" % filef)
            fp.write(json.dumps(data, indent=1) + "\n")

        if args.sign:
            sys.stderr.write("signing %s\n" % filef)
            toolutil.signjson_file(filef)

    return

if __name__ == '__main__':
    sys.exit(main())

# vi: ts=4 expandtab
