# -*- coding: UTF-8 -*-

# author:   James Zo
# email:    james_email@sina.cn

from py.mysqltable import *
from py.mail import *
import os
import sys
import logging
import time
from py.util import *

if __name__ == "__main__":
    if len(sys.argv) <= 1:
        logging.error("Failed for no config file appointed.")
        exit()
    open_cfg(sys.argv[1])

    mysql_host = cfg.get('mysql', 'host')
    mysql_user = cfg.get('mysql', 'user')
    mysql_passwd = cfg.get('mysql', 'passwd')
    mysql_sql = cfg.get('mysql', 'sql')

    export_file = cfg.get('export', 'file')

    email_content = cfg.get('email', 'content')
    email_sender = cfg.get('email', 'sender')
    email_passwd = cfg.get('email', 'passwd')
    email_smtp_server = cfg.get('email', 'smtp_server')
    email_to = cfg.get('email', 'to')
    email_cc = cfg.get('email', 'cc')
    email_subject = cfg.get('email', 'subject') + "---" + time.strftime('%Y-%m-%d',time.localtime(time.time()))

    mysqltable = MysqlTable(mysql_host, mysql_user, mysql_passwd, mysql_sql)
    mysqltable.write(export_file)
    mysqltable.copy_for_windows()
    mysqltable.close()

    logger().info("Export to " + export_file)

    em = Email()
    em.add_to(email_to)
    em.add_cc(email_cc)
    em.set_sender(email_sender, email_passwd)
    em.set_subject(email_subject)
    em.add_content(email_content)
    em.add_file(export_file)

    (path,tempfilename) = os.path.split(export_file);  
    (shortname,extension) = os.path.splitext(tempfilename);  
    win_file = path + os.path.sep + shortname + "_win"  +  extension
    em.add_file(win_file)
    em.send(email_smtp_server)

    logger().info("Send exported file to " + str(email_to + email_cc))
