# -*- coding: utf-8 -*-

import sys
import os
import re
import unittest

script_dir = os.path.dirname(os.path.abspath(__file__))
base_dir = script_dir + os.sep + '../'
if not base_dir in sys.path:
    sys.path.insert(0, base_dir)
    
from mail_parser import *

class ComponentManagerStub(object):
    components = {}
    
    def __init__(self):
        self.config = ConfigStub()

    def component_activated(self, dummy):
        pass

    def get_db_cnx(self):
        return DBStub()
    
class ConfigStub(object):
    def get(self, tag, key, default=None):
        return 'utf-8'

class DBStub(object):
    def __init__(self, row=None):
        self.row = row
    
    def cursor(self):
        print "cursor"
        return self
    
    def execute(self, sql , args):
        print "excecute"
        return self
    
    def fetchone(self):
        print "fetchone"
        return self.row 
    
    def commit(self):
        print "commit"
        
class MailParserTest(unittest.TestCase):

    def setUp(self):
        self.env = ComponentManagerStub()
        self.db = DBStub()
    
    def test_parse_header_simple(self):
        msgs = read_mail('simple.mbx')
        
        mail_parser = MailParser(self.env, self.db)
        
        header = mail_parser.parse_header(msgs[0])
        
        self.assertEquals('100@example.com', header.messageid)
        self.assertEquals('Test Mail', header.subject)
        
        header = mail_parser.parse_header(msgs[1])
        
        self.assertEquals('200@example.com', header.messageid)
        self.assertEquals('Test Mail 2', header.subject)
        
    
    def test_parse_header_japanese(self):
        msgs = read_mail('japanese.mbx')
        
        mail_parser = MailParser(self.env, self.db)
        
        header = mail_parser.parse_header(msgs[0])
        
        self.assertEquals(u'日本語のテスト(JIS)', header.subject)
        
def read_mail(msgfile_path):
    import mailbox
    
    def msgfactory(fp):
        try:
            return email.message_from_file(fp)
        except email.Errors.MessageParseError:
            # Don't return None since that will
            # stop the mailbox iterator
            return ''

    fp = open(msgfile_path,"rb")
    mbox = mailbox.UnixMailbox(fp, msgfactory)

    counter =1
    msg = mbox.next()
    
    msgs = []
    
    while msg is not None:
        try:
            msgs.append(msg)
        except Exception, e:
            traceback.print_exc(e)

        if counter > 10000:
            break
        msg = mbox.next()
        counter = counter + 1

    fp.close()
    return msgs


if __name__ == '__main__':
    unittest.main()