#!/usr/bin/env python
# vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4

from datetime import datetime
from time import time
from reviewday.gerrit import reviews as gerrit_reviews
from reviewday.util import create_report
from reviewday.launchpad import LaunchPad
from reviewday.mergeprop import MergeProp
from optparse import OptionParser
import os
import yaml

optparser = OptionParser()

optparser.add_option('-o', '--out-dir', dest='out_dir',
                     help='set output directory [default = %default]',
                     default='out_report', type='string')
optparser.add_option('-p', '--project-file', dest='project_file',
                     help='A YAML or JSON file specifying the project list',
                     type='string')

(options, args) = optparser.parse_args()

lp = LaunchPad()

projects = {}

cur_timestamp = time()

PROJECTS = [
    'ceilometer',
    'cinder',
    'diskimage-builder',
    'glance',
    'heat',
    'horizon',
    'identity-api',
    'ironic',
    'keystone',
    'neutron',
    'nova',
    'os-apply-config',
    'os-collect-config',
    'os-net-config',
    'os-refresh-config',
    'python-ceilometerclient',
    'python-cinderclient',
    'python-glanceclient',
    'python-heatclient',
    'python-ironicclient',
    'python-keystoneclient',
    'python-neutronclient',
    'python-novaclient',
    'python-saharaclient',
    'python-swiftclient',
    'python-troveclient',
    'python-tuskarclient',
    'python-zaqarclient',
    'sahara',
    'sahara-dashboard',
    'sahara-extra',
    'sahara-image-elements',
    'swift',
    'tempest',
    'tripleo-heat-templates',
    'tripleo-image-elements',
    'tripleo-incubator',
    'trove',
    'trove-integration',
    'tuskar',
    'tuskar-ui',
    'zaqar',
    ]

proj_names = PROJECTS
lp_projects = {}
if options.project_file:
    if os.path.exists(options.project_file):
        with open(options.project_file) as cf:
            proj_names = []
            for proj in yaml.load(cf.read()).get("projects"):
                name = proj['name']
                proj_names.append(name)
                if 'launchpad_project' in proj:
                    lp_projects[name] = proj['launchpad_project']

for project in proj_names:
    if project not in projects:
        projects[project] = []
    for review in gerrit_reviews(project):
        try:
            mp = MergeProp(lp, review, cur_timestamp)
            if not mp.is_wip:
                projects[project].append(mp)
        except:
            print 'Error creating merge prop %s' % review

dts = str(datetime.utcnow())[0:19]
name_space = {"projects": projects, "dts": dts}
out_dir = options.out_dir
create_report(out_dir, name_space)
