#!/usr/bin/env python
# coding=utf-8

"""

   Copyright 2015 Andreas Würl

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

"""

from __future__ import print_function

from optparse import OptionParser
import os
import shelve

from citools.data import TestReport
from citools.jenkins.report import Report


def merge_suites(suites_1, suites_2):
    suites_by_name_1 = create_dict_by_name(suites_1)
    suites_by_name_2 = create_dict_by_name(suites_2)

    for key, value in suites_by_name_2.iteritems():
        if key in suites_by_name_1 and value.timestamp <= suites_by_name_1[key].timestamp:
            continue
        suites_by_name_1[key] = value

    return suites_by_name_1.values()


def create_dict_by_name(suites):
    return dict((suite.name, suite) for suite in suites)


def print_dict(name, data):
    print(name, "#" + str(len(data)))
    for key, value in data.iteritems():
        print("  ", key, value)


if __name__ == '__main__':

    parser = OptionParser()

    (options, args) = parser.parse_args()

    report = Report()

    jenkins_url = os.environ['JENKINS_URL']

    if jenkins_url is None:
        raise RuntimeError("Jenkins Url should be set.")

    sources = args[:-1]
    target = args[-1]

    suites_by_module = {}

    source_jobs = []

    for source in sources:
        db_file_name = source + ".db"
        if os.path.exists(db_file_name):
            db = shelve.open(db_file_name)

            source_report = db.get('report', None)
            print("source " + source + " " + str(source_report))

            for module, suites in source_report.suites_by_module.iteritems():
                suites_by_module[module] = merge_suites(suites_by_module[module],
                                                        suites) if module in suites_by_module else suites

            db.close()
            source_jobs.append({'name': source, 'build_number': source_report.build_number})

    target_report = TestReport(target, suites_by_module, 0, False)
    db = shelve.open(target + ".db")

    db['report'] = target_report
    db['source_jobs'] = source_jobs

    db.close()

    print("target " + target + " " + str(target_report))
    print("source jobs:")
    for source_job in source_jobs:
        job_name = source_job['name']
        build_number = str(source_job['build_number'])
        print("  " + job_name + " #" + build_number + " "
              + jenkins_url + "job/" + job_name + "/" + build_number)
