#!/usr/bin/env python

import os
from optparse import OptionParser
from urllib import urlopen
from subprocess import Popen, PIPE

dansk_gruppen_email = 'dansk@dansk-gruppen.dk'

class DanskGruppen:
    def __init__(self, email=dansk_gruppen_email, dryrun=False):
        self.email = email
        self.status_page_url = 'http://wiki.dansk-gruppen.dk/index.php/Status'
        self.ordlisten = 'http://www.klid.dk/dansk/ordlister/ordliste.html'
        self.damned_lies_url = 'http://l10n.gnome.org/languages/da/'
        self.dryrun = dryrun

    def reserve(self, name, project=None):
        subject = 'Reserverer %s' % name
        if project is not None:
            subject = '[%s] %s' % (project, subject)
        self.send_email(subject, '')
        # OK send to mailing list
        # X check on status page
        # X register on gnome page?
        # X register on status page
        # X optional extra comments

    def integrate(self, pofile, project=None):
        subject = '%s til integrering' % pofile.rstrip('.da.po')
        if project is not None:
            subject = '[%s] %s' % (project, subject)
        errcode = os.system('msgfmt -cv -o /dev/null %s' % pofile)
        if errcode != 0:
            raise ValueError('Target is not a valid po-file')
        self.send_email(subject, '', attachment=pofile)
        print 'Please update status for %s on status page' % pofile
        print self.status_page_url
                                                      
        if project.upper() == 'GNOME':
            print 'Please update status on damned lines'
            print self.damned_lies_url
        # X check on status page
        # OK run msgfmt on pofile
        # OK send to mailing list as attachment
        # X *or* upload to some dir, sending path
        # X optional extra comments
        # X update status page

    def proofread(self, podiff_or_pofile, project=None):
        fname = podiff_or_pofile
        if fname.endswith('.podiff'):
            name = fname.rstrip('.podiff')
            type = 'podiff'
        elif fname.endswith('.po'):
            name = fname.rstrip('.po')
            type = 'po'
        else:
            name = fname
            type = 'unknown'
        name = name.rstrip('.da')
        if type == 'podiff':
            line = open(fname).readlines()[-1]
            msgcount = int(line.split()[-1])
        elif type == 'po':
            msgfmt = Popen(('msgfmt -cv -o /dev/null %s' % fname).split(),
                           stderr=PIPE)
            errcode = msgfmt.wait()
            msgcount = None
            for token in msgfmt.stderr.readlines()[-1].split():
                try:
                    msgcount = int(token)
                except:
                    pass
            assert msgcount is not None
        
        subject = '%s til genneml\xc3\xa6sning (%s)' % (name, msgcount)
        if project is not None:
            subject = '[%s] %s' % (project, subject)
        os.system('echo "%s"' % subject)
        text = open(fname).read()
        self.send_email(subject, text)
        # X check on status page
        # OK print number of msgs
        # X send as attachment and
        # OK send as text
        # X optional extra comments
        # X update status page

    def printpage(self, url, dummyfile=None):
        if dummyfile is not None:
            html = open(dummyfile)
        elif self.dryrun:
            echo = Popen('echo hello world'.split(), 
                         stdout=PIPE)
            html = echo.stdout
        else:
            html = urlopen(url)
        
        html2text = Popen('html2text', stdin=html)
        html2text.wait()
        

    def print_status_page(self, dummyfile=None):
        self.showpage(self.status_page_url)

    def print_ordlisten(self, dummyfile=None):
        self.printpage(self.ordlisten)

    def send_email(self, subject, msg, address=None, attachment=None):
        if address is None:
            address = self.email
        cmd = 'echo "%s" | '
        if self.dryrun:
            print 'dry run send'
            print '  subject', subject
            print '  msg len', len(msg)
            print '  attachment', attachment
            print '  address', address
        else:
            mutt = Popen(['mutt', '-s', subject, address], stdin=PIPE)
            print >> mutt.stdin, msg
            mutt.stdin.close()
            mutt.wait()
            print 'Email SENT to %s regarding %s' % (address, subject)


def build_parser():
    p = OptionParser()
    p.add_option('--status', action='store_true',
                 help='print Dansk-gruppens wiki status page to standard '
                 'output.')
    p.add_option('--ordlisten', action='store_true',
                 help='print Dansk-gruppens ordliste')
    p.add_option('--reserve', metavar='FILE', 
                 help='reserve FILE for translation')
    p.add_option('--proofread', metavar='FILE',
                 help='request proofreading of FILE')
    p.add_option('--integrate', metavar='FILE', 
                 help='request integration of FILE')
    p.add_option('--project',
                 help='project in question (Fedora, KDE, GNOME, ...)')
    p.add_option('--email', default=dansk_gruppen_email,
                 help='treat this as email address of '
                 'dansk-gruppen. [default: %default]')
    p.add_option('--dry', action='store_true', default=True,
                 help='dry run (test code doing nothing).  This is the '
                 'default behaviour so far')
    p.add_option('--seriously', action='store_false', dest='dry',
                 help='opposite of dry run')
    return p

def main():
    parser = build_parser()
    opts, args = parser.parse_args()

    assert isinstance(opts.dry, bool)
    if opts.dry:
        email = 'asklarsen@gmail.com'
    else:
        email = opts.email
    
    dg = DanskGruppen(email, dryrun=opts.dry)
    
    if not opts.project:
        parser.error('Please specify a project using e.g. --project GNOME')

    if opts.status:
        dg.print_status_page()
    
    if opts.ordlisten:
        dg.print_ordlisten()

    if opts.reserve:
        dg.reserve(opts.reserve, opts.project)

    if opts.proofread:
        dg.proofread(opts.proofread, opts.project)

    if opts.integrate:
        dg.integrate(opts.integrate, opts.project)


if __name__ == '__main__':
    main()
    #dg = DanskGruppen('asklarsen@gmail.com')
    #dg.print_status_page()
    #send_email('autotest', 'asklarsen@gmail.com', 'automatic test')

