# Path: productporter/utils/helper.py
# def query_products(spec_day=None):
#     """ get all the products of the day """
#     day = spec_day
#     if not day:
#         day = format_date(datetime.date.today())
#     posts = Product.query.filter(Product.date==day).\
#         order_by(Product.votes_count.desc()).all()
# 
#     # when not specific a day and the content is empty, we show yesterday's data
#     if not spec_day and len(posts) == 0:
#         delta = datetime.timedelta(days=-1)
#         d = datetime.date.today() + delta
#         day = format_date(d)
#     posts = Product.query.filter(Product.date==day).\
#         order_by(Product.votes_count.desc()).all()
# 
#     # when spec_day is some old date and data is empty, we pull from PH server
#     if spec_day and len(posts) == 0:
#         today = datetime.date.today()
#         ymd = spec_day.split('-')
#         spec_date = datetime.date(int(ymd[0]), int(ymd[1]), int(ymd[2]))
#         if spec_date < today:
#             day = spec_day
#             pull_and_save_posts(day)
#             posts = Product.query.filter(Product.date==day).\
#                 order_by(Product.votes_count.desc()).all()
#     return day, posts
# 
# def format_date(d):
#     """ format a datetime.date object to string """
#     return '%04d-%02d-%02d' % (d.year, d.month, d.day)
# 
# def query_top_voted_products(days_ago=2, limit=10):
#     """ query to voted products days ago """
#     delta = datetime.timedelta(days=-days_ago)
#     d2 = datetime.date.today()
#     d1 = d2 + delta
#     return Product.query.filter(Product.date.between(d1, d2)).\
#         order_by(Product.votes_count.desc()).limit(limit).offset(0).all()
# 
# def query_search_products(keyword, limit=10):
#     """ search product in product's name and tagline """
#     k = '%%%s%%' % (keyword)
#     return Product.query.filter(db.or_(Product.name.like(k), \
#         Product.tagline.like(k))).order_by(Product.votes_count.desc()).\
#         limit(limit).offset(0).all()
# 
# def send_mail(subject, recipient, body, subtype='plain', as_attachment=False):
#     """ send mail """
#     import smtplib
#     from email.mime.multipart import MIMEMultipart
#     from email.mime.text import MIMEText
# 
#     sender = current_app.config["MAIL_SENDER"]
#     smtpserver = current_app.config["MAIL_SERVER"]
#     username = current_app.config["MAIL_USERNAME"]
#     password = current_app.config["MAIL_PASSWORD"]
# 
#     # attachment
#     if as_attachment:
#         msgroot = MIMEMultipart('related')
#         msgroot['Subject'] = subject
#         att = MIMEText(body, 'base64', 'utf-8')
#         att["Content-Type"] = 'text/plain'
#         att["Content-Disposition"] = \
#             'attachment; filename="%s.txt"' % (time.strftime("%Y%m%d"))
#         msgroot.attach(att)
#     else:
#         msgroot = MIMEText(body, subtype, 'utf-8')
#         msgroot['Subject'] = subject
# 
#     smtp = smtplib.SMTP()
#     smtp.connect(smtpserver)
#     smtp.login(username, password)
#     smtp.sendmail(sender, recipient, msgroot.as_string())
#     smtp.quit()


import hashlib, time
import xml.etree.ElementTree as ET
from flask import Blueprint, request, current_app, redirect, url_for
from productporter.weixin.consts import *
from productporter.utils.helper import query_products, format_date, \
    query_top_voted_products, query_search_products, send_mail
    info = "Mail sent to " + receiver
    if products is not None and len(products) > 0:
        body = ""
        for prod in products:
            item = WX_TEXT_TPL % (prod.name, prod.redirect_url, prod.tagline)
            body += item
        try:
            send_mail(
                subject='PH - ' + time.strftime("%Y%m%d"),
                recipient=receiver,
                body=body,
                subtype="html",
                as_attachment=True)
        except:
            info = "Failed to send mail to " + receiver
    else:
        info = ERROR_INFO

    if msg is not None:
        return response_text_msg(msg, info)
    else:
        return info + "\n"

def push_day_top_voted_products(msg):
    """ push day top voted """
    products = query_top_voted_products(days_ago=2, limit=10)
    return push_products(msg, products)

def push_week_top_voted_products(msg):
    """ push week top voted """

# Path: productporter/utils/helper.py
# def query_products(spec_day=None):
#     """ get all the products of the day """
#     day = spec_day
#     if not day:
#         day = format_date(datetime.date.today())
#     posts = Product.query.filter(Product.date==day).\
#         order_by(Product.votes_count.desc()).all()
# 
#     # when not specific a day and the content is empty, we show yesterday's data
#     if not spec_day and len(posts) == 0:
#         delta = datetime.timedelta(days=-1)
#         d = datetime.date.today() + delta
#         day = format_date(d)
#     posts = Product.query.filter(Product.date==day).\
#         order_by(Product.votes_count.desc()).all()
# 
#     # when spec_day is some old date and data is empty, we pull from PH server
#     if spec_day and len(posts) == 0:
#         today = datetime.date.today()
#         ymd = spec_day.split('-')
#         spec_date = datetime.date(int(ymd[0]), int(ymd[1]), int(ymd[2]))
#         if spec_date < today:
#             day = spec_day
#             pull_and_save_posts(day)
#             posts = Product.query.filter(Product.date==day).\
#                 order_by(Product.votes_count.desc()).all()
#     return day, posts
# 
# def format_date(d):
#     """ format a datetime.date object to string """
#     return '%04d-%02d-%02d' % (d.year, d.month, d.day)
# 
# def query_top_voted_products(days_ago=2, limit=10):
#     """ query to voted products days ago """
#     delta = datetime.timedelta(days=-days_ago)
#     d2 = datetime.date.today()
#     d1 = d2 + delta
#     return Product.query.filter(Product.date.between(d1, d2)).\
#         order_by(Product.votes_count.desc()).limit(limit).offset(0).all()
# 
# def query_search_products(keyword, limit=10):
#     """ search product in product's name and tagline """
#     k = '%%%s%%' % (keyword)
#     return Product.query.filter(db.or_(Product.name.like(k), \
#         Product.tagline.like(k))).order_by(Product.votes_count.desc()).\
#         limit(limit).offset(0).all()
# 
# def send_mail(subject, recipient, body, subtype='plain', as_attachment=False):
#     """ send mail """
#     import smtplib
#     from email.mime.multipart import MIMEMultipart
#     from email.mime.text import MIMEText
# 
#     sender = current_app.config["MAIL_SENDER"]
#     smtpserver = current_app.config["MAIL_SERVER"]
#     username = current_app.config["MAIL_USERNAME"]
#     password = current_app.config["MAIL_PASSWORD"]
# 
#     # attachment
#     if as_attachment:
#         msgroot = MIMEMultipart('related')
#         msgroot['Subject'] = subject
#         att = MIMEText(body, 'base64', 'utf-8')
#         att["Content-Type"] = 'text/plain'
#         att["Content-Disposition"] = \
#             'attachment; filename="%s.txt"' % (time.strftime("%Y%m%d"))
#         msgroot.attach(att)
#     else:
#         msgroot = MIMEText(body, subtype, 'utf-8')
#         msgroot['Subject'] = subject
# 
#     smtp = smtplib.SMTP()
#     smtp.connect(smtpserver)
#     smtp.login(username, password)
#     smtp.sendmail(sender, recipient, msgroot.as_string())
#     smtp.quit()


# Path: productporter/weixin/views.py
import hashlib, time
import xml.etree.ElementTree as ET
from flask import Blueprint, request, current_app, redirect, url_for
from productporter.weixin.consts import *
from productporter.utils.helper import query_products, format_date, \
    query_top_voted_products, query_search_products, send_mail

    info = "Mail sent to " + receiver
    if products is not None and len(products) > 0:
        body = ""
        for prod in products:
            item = WX_TEXT_TPL % (prod.name, prod.redirect_url, prod.tagline)
            body += item
        try:
            send_mail(
                subject='PH - ' + time.strftime("%Y%m%d"),
                recipient=receiver,
                body=body,
                subtype="html",
                as_attachment=True)
        except:
            info = "Failed to send mail to " + receiver
    else:
        info = ERROR_INFO

    if msg is not None:
        return response_text_msg(msg, info)
    else:
        return info + "\n"

def push_day_top_voted_products(msg):
    """ push day top voted """
    products = query_top_voted_products(days_ago=2, limit=10)
    return push_products(msg, products)

def push_week_top_voted_products(msg):
    """ push week top voted """

    products = query_top_voted_products(days_ago=7, limit=10)