#!/usr/bin/env python3
import json
import argparse
import smtplib
from keys import *
from email.message import EmailMessage
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

FROM_ADDR = 'noreply@emblem-notify.euphon.net'

def send_email(to, subject, body):
    msg = EmailMessage()
    msg.set_content(body)
    msg['Subject'] = subject
    msg['From'] = FROM_ADDR
    msg['To'] = to

    s = smtplib.SMTP('smtpdm.aliyun.com')
    s.login(FROM_ADDR, 'N72yBNi4cJw')
    s.send_message(msg)
    s.quit()

def send_sms_code(mobile, code):
    ak = aliyun_prod_key['access_key']
    sk = aliyun_prod_key['secret']
    client = AcsClient(ak, sk, 'cn-shenzhen')
    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https') # https | http
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')

    request.add_query_param('RegionId', "cn-shenzhen")
    request.add_query_param('PhoneNumbers', mobile)
    request.add_query_param('SignName', "themblem")
    request.add_query_param('TemplateCode', 'SMS_280201599')
    request.add_query_param('TemplateParam', "{\"code\":\"%s\"}" % code)

    print(request)
    response = client.do_action(request).decode()
    print(response)
    r = json.loads(response)
    if r.get("Code") != "OK":
        raise Exception(r["Message"])


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--to")
    parser.add_argument("--subject")
    parser.add_argument("--body", default='no content')
    parser.add_argument("--mobile")
    parser.add_argument("--verify-code", '-c')
    return parser.parse_args()

def main():
    args = parse_args()
    if args.to and args.subject:
        send_email(args.to, args.subject, args.body)
    if args.mobile and args.verify_code:
        send_sms_code(args.mobile, args.verify_code)

if __name__ == "__main__":
    main()
