#!/usr/bin/env python3
#
# Copyright (C) 2012-2017 Chris Cummins.
#
# This file is part of emu.
#
# Emu 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, either version 3 of the License, or (at your
# option) any later version.
#
# Emu 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 General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with emu.  If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import print_function

import os
import re
import subprocess
import sys
import tempfile
from sys import exit

from emu import *
from emu import io


def print_dict(d):
    for prop in d:
        if not re.match("^(snapshot|status)$", prop):
            print("{:<14} {:<50}"
                  .format(" ".join(prop.split("-")).capitalize() + ":",
                          d[prop]))

def main(argv, argc):
    parser = Parser()
    parser.add_option("-n", "--limit", action="store", type="int",
                      dest="limit", default=0)
    parser.add_option("-s", "--short-log", action="store_true", dest="short",
                      default=False)
    (options, args) = parser.parse_args()

    snapshots = parser.parse_snapshots(Source(options.source_dir), require=True)

    # Setup pagination
    tmp_path = tempfile.mkstemp()[1]
    tmp_file = open(tmp_path, 'a')
    sys.stdout = tmp_file

    # Zero or negative limit values means show all snapshots
    if options.limit <= 0:
        options.limit = len(snapshots)

    # Determine whether we need to print sink names or not:
    print_sink_names = False
    if not options.short:
        current_sink = snapshots[0].sink
        for snapshot in snapshots[:options.limit]:
            if snapshot.sink != current_sink:
                print_sink_names = True

    # Print logs:
    current_sink = None
    no_of_snapshots = len(snapshots[:options.limit])
    i = 0
    for snapshot in snapshots[:options.limit]:
        i += 1

        # Print sink names when required:
        if print_sink_names and snapshot.sink != current_sink:
            current_sink = snapshot.sink
            print(colourise("{0}:".format(current_sink.name),
                            Colours.INFO))

        # Log:
        id = colourise(snapshot.id.snapshot_name, Colours.SNAPSHOT)
        if options.short:
            s = "{0}  {1}".format(snapshot.id, snapshot.node.name())
        else:
            s = "snapshot       {0}".format(id)

        print(s)

        if not options.short:
            print_dict(snapshot.node.section("Snapshot"))
            print_dict(snapshot.node.section("Tree"))
            if io.verbose_enabled:
                print_dict(snapshot.node.section("Sink"))
                print_dict(snapshot.node.section("Emu"))
            if i < no_of_snapshots:
                print()

    # Flush pagination
    tmp_file.flush()
    tmp_file.close()
    p = subprocess.Popen(['less', tmp_path], stdin=subprocess.PIPE)
    p.communicate()
    sys.stdout = sys.__stdout__

    return 0


if __name__ == "__main__":
    argv = sys.argv[1:]
    ret = main(argv, len(argv))
    exit(ret)
