#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#  Script for producing Reports from data in ElasticSearch
#
# Copyright (C) 2017 Bitergia
#
# This program 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.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# git.Authors:
#   Alvaro del Castillo San Felix <acs@bitergia.com>
#

import argparse
import logging
import os
import sys

from datetime import date, timedelta, timezone

from dateutil import parser

# To execute it without installing it
sys.path.insert(0, '.')
from report.report import Report

from mordred.config import Config

def get_params():
    """Parse command line arguments"""

    parser = argparse.ArgumentParser()

    parser.add_argument('-d', '--data-dir', default='data',
                        help="Directory to store the data results")
    parser.add_argument('-e', '--end-date', default='now',
                        help="End date for the report (UTC) (<)")
    parser.add_argument('-f', '--filters', nargs='*',
                        help='Filters to be applied to all the report data: "field1:value1" "field2:value2". \
                              Use *field for the inverse filter.')
    parser.add_argument('-g', '--debug', dest='debug', action='store_true')
    parser.add_argument('-i', '--interval', default='month', help="Analysis interval (month (default), quarter, year)")
    parser.add_argument('-s', '--start-date', default='2015-01-01',
                        help="Start date for the report (UTC) (>=)")
    parser.add_argument('--offset', help="Offset to be used in date histogram aggregations (e.g.: +31d)")
    parser.add_argument('-u', '--elastic-url', help="Elastic URL with the enriched indexes")
    parser.add_argument('--data-sources', nargs='*',
                        help="Data source for the report (git, ...)")
    parser.add_argument('-n', '--name', help="Report name")
    parser.add_argument('-m', '--mordred-config', help="Mordred config file")
    parser.add_argument('-p', '--projects', action='store_true', help="Generate per project data")

    return parser.parse_args()


def get_offset_days(offset):
    """ offset format supported: '+31d' """
    days = int(offset[1:-1])
    return days


if __name__ == '__main__':

    args = get_params()

    if args.debug:
        logging.basicConfig(level=logging.DEBUG, format='[%(asctime)s] %(message)s')
        logging.debug("Debug mode activated")
    else:
        logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    logging.getLogger("requests").setLevel(logging.WARNING)

    elastic = args.elastic_url
    report_name = args.name
    data_dir = args.data_dir
    data_sources = args.data_sources

    if not os.path.exists(data_dir):
        os.makedirs(data_dir)

    # All the dates must be UTC, including those from command line
    if args.end_date == 'now':
        end_date = parser.parse(date.today().strftime('%Y-%m-%d')).replace(tzinfo=timezone.utc)
    else:
        end_date = parser.parse(args.end_date).replace(tzinfo=timezone.utc)
    # The end date is not included, the report must finish the day before
    end_date += timedelta(microseconds=-1)
    start_date = parser.parse(args.start_date).replace(tzinfo=timezone.utc)

    offset = args.offset if args.offset else None

    # if offset, start and end must be adjusted to it

    if offset:
        logging.debug("Adjusting range %s-%s for offset %s", start_date, end_date, offset)
        offset_days = get_offset_days(offset)
        start_date = start_date + timedelta(days=offset_days)
        end_date = end_date + timedelta(days=offset_days)
        logging.debug("New range %s-%s with offset %s",
                      start_date, end_date, offset)

    if args.mordred_config:
        # Read the mordred config file and configure the data sources according to it
        config = Config(args.mordred_config)
        data_sources = config.get_data_sources()
        elastic = config.conf['es_enrichment']['url']
        if not args.name:
            report_name = config.conf['general']['short_name']

    report = Report(elastic, start=start_date,
                    end=end_date, data_dir=data_dir,
                    filters=Report.get_core_filters(args.filters),
                    interval=args.interval,
                    offset=offset,
                    data_sources=data_sources,
                    report_name=report_name,
                    projects=args.projects)
    report.create()
