#!/usr/local/bin/python3.8
# -*- coding: utf-8 -*-
#
# Copyright 2014  Alex Merry <alex.merry@kdemail.net>
# Copyright 2014  Aurélien Gâteau <agateau@kde.org>
# Copyright 2014  Alex Turbov <i.zaufi@gmail.com>
# Copyright 2016  Olivier Churlaud <olivier@churlaud.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import logging
import codecs
import os
import sys
import time
import datetime

from urllib.request import urlretrieve

from kapidox import generator, utils, argparserutils, preprocessing, hlfunctions

try:
    from kapidox import depdiagram
    DEPDIAGRAM_AVAILABLE = True
except ImportError:
    DEPDIAGRAM_AVAILABLE = False


def download_kde_identities():
    """Download the "accounts" file on the KDE SVN repository in order to get
       the KDE identities with their name and e-mail address
    """
    cache_file = os.path.join(utils.cache_dir(), 'kde-accounts')
    needs_download = True
    if os.path.exists(cache_file):
        logging.debug("Found cached identities file at %s", cache_file)
        # not quite a day, so that generation on api.kde.org gets a fresh
        # copy every time the daily cron job runs it
        yesterday = time.time() - (23.5 * 3600)
        if os.path.getmtime(cache_file) > yesterday:
            needs_download = False
        else:
            logging.debug("Cached file too old; updating")
    if needs_download:
        logging.info("Downloading KDE identities")
        try:
            if not utils.svn_export(
                    'svn://anonsvn.kde.org/home/kde/trunk/kde-common/accounts',
                    cache_file,
                    overwrite=True):
                logging.debug("Falling back to using websvn to fetch "
                              "identities file")
                urlretrieve('https://websvn.kde.org/*checkout*/trunk/kde-common/accounts',
                            cache_file)
        except Exception as e:
            if os.path.exists(cache_file):
                logging.error('Failed to update KDE identities: %s', e)
            else:
                logging.error('Failed to fetch KDE identities: %s', e)
                return None

    maintainers = {}

    with codecs.open(cache_file, 'r', encoding='utf8') as f:
        for line in f:
            parts = line.strip().split()
            if len(parts) >= 3:
                maintainers[parts[0]] = {
                    'name': ' '.join(parts[1:-1]),
                    'email': parts[-1]
                    }

    return maintainers


def main():
    kde_copyright = '1996-' + str(datetime.date.today().year) + ' The KDE developers'
    get_maintainers = download_kde_identities

    hlfunctions.do_it(maintainers_fct=get_maintainers,
                      copyright=kde_copyright)


if __name__ == "__main__":
    main()
