# coding: utf8
# Debian Contributors data source data mining tools
#
# Copyright (C) 2013--2014  Enrico Zini <enrico@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
from .. import scanner
from ..parser import Fail
from ..types import Identifier

__all__ = ["Bts"]


class Bts(scanner.Scanner):
    """
    Parses the debbugs spool directories collecting contributions from mail
    headers.

    Example::
        contribution: correspondant
        method: bts
        dirs: /srv/bugs.debian.org/spool/db-h/ /srv/bugs.debian.org/spool/archive/
        url: https://bugs.debian.org/cgi-bin/pkgreport.cgi?correspondent={email}
    """
    dirs = scanner.GlobField(blank=False, help_text="""
                             debbugs spool directories to scan. You can give
                             one or more, and even use shell-style globbing.
                             """)
    threshold = scanner.IntegerField(default=5, help_text="""
                                     Minimum number of mails that need to exist
                                     in the BTS for an email address to be
                                     considered
                                     """)
    url = scanner.CharField(help_text="""
                            template used to build URLs to link to people's contributions.
                            ``{email}`` will be replaced with the email address
                            """)

    def scan(self):
        from .utils.bts import DebbugsScanner
        scan = DebbugsScanner()
        for d in self.dirs:
            scan.scan_dir(d)

        threshold = self.threshold
        tpl = self.url
        for email, (count, contrib) in scan.data.items():
            if count < threshold: continue
            ident = Identifier("email", email)
            try:
                ident.validate()
            except Fail:
                continue
            yield ident, contrib.begin, contrib.end, ( tpl.format(email=email) if tpl else None )
