#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2018             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.


def _split_subsections(info):
    subname = ''
    subsections = {}
    for row in info:
        if not row:
            continue
        if row[0].startswith('[[[') and row[0].endswith(']]]'):
            subname = row[0].strip('[]')
            continue
        subsections.setdefault(subname, []).append(row)
    return subsections


def parse_docker_node_images(info):
    # pylint: disable=undefined-variable
    version = docker_get_version(info)

    if version is None:
        subsections = _split_subsections(info)
        return parse_legacy_docker_node_images(subsections)

    subsections = _split_subsections(info[1:])
    i_images = (docker_json_get_obj(i) for i in subsections.get('images', []))
    images = {i["Id"]: i for i in i_images if i is not None}
    i_containers = (docker_json_get_obj(c) for c in subsections.get('containers', []))
    containers = {c["Id"]: c for c in i_containers if c is not None}

    running_images = [c['Image'] for c in containers.itervalues()]

    for image_id in images:
        images[image_id]['amount_containers'] = running_images.count(image_id)

    return {'images': images, 'containers': containers}


def inv_docker_node_images(info, inventory_tree, status_data_tree):
    parsed = parse_docker_node_images(info)
    images = parsed.get("images", {})
    path = "software.applications.docker.images:"
    inv_node = inventory_tree.get_list(path)
    status_node = status_data_tree.get_list(path)

    for image_id, image in sorted(images.iteritems()):
        repodigests = ", ".join(image.get("RepoDigests", []))
        fallback_repotag = repodigests.split('@', 1)[:1] if '@' in repodigests else []
        inv_node.append({
            "repotags": ", ".join(image.get("RepoTags", fallback_repotag)),
            "repodigests": repodigests,
            "id": docker_get_short_id(image_id),  # pylint: disable=undefined-variable
            "creation": image["Created"],
            "size": image["VirtualSize"],
            "labels": docker_format_labels(image),  # pylint: disable=undefined-variable
        })

        status_node.append({
            "id": docker_get_short_id(image_id),  # pylint: disable=undefined-variable
            "amount_containers": image["amount_containers"],
        })

    containers = parsed.get("containers", {})
    status_node = status_data_tree.get_list("software.applications.docker.containers:")

    for container_id, container in sorted(containers.iteritems()):
        status_node.append({
            "id": docker_get_short_id(container_id),  # pylint: disable=undefined-variable
            "image": docker_get_short_id(container["Image"]),  # pylint: disable=undefined-variable
            "name": container["Name"],
            "creation": container["Created"],
            "labels": docker_format_labels(container),  # pylint: disable=undefined-variable
            "status": container.get("State", {}).get("Status"),
        })


inv_info['docker_node_images'] = {  # pylint: disable=undefined-variable
    'includes': ['legacy_docker.include', 'docker.include'],
    'inv_function': inv_docker_node_images,
    'has_status_data': True,
}
