import base64
import datetime
import smtplib
import os
import sqlite3
from email.mime.text import MIMEText
from email.header import Header

from google_auth_httplib2 import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient import errors
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly',
          'https://www.googleapis.com/auth/gmail.send']


def create_message(sender_name, sender_mail, to, subject, message_text):
    message = MIMEText(message_text, 'html')
    message['to'] = to
    message['from'] = Header(f'{sender_name} <{sender_mail}>', 'utf-8')
    message['subject'] = subject

    return message


def send_message(to_email, mime_message):
    try:
        smtp = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        smtp.login(os.environ['EMAIL_USER'], os.environ['EMAIL_PASSWD'])
        smtp.sendmail(os.environ['EMAIL_USER'], to_email, mime_message.as_string())
        smtp.quit()

    except errors.HttpError as error:
        print('An error occurred: %s' % error)


def allow_mail_send():
    current_date = datetime.date.today()

    # db setting
    send_mail_db = sqlite3.connect("mail_send_cnt.db")
    db_cursor = send_mail_db.cursor()
    db_cursor.execute(
        "SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}'".format(table_name='send_history'))
    if not db_cursor.fetchone():
        db_cursor.execute("create table send_history (send_date date)")

    # 오늘 전날 발송된게 확인된 것들은 살펴보지 않고 지운다.
    db_cursor.execute("delete from send_history where send_date < '{0}'".format(current_date))

    # 오늘 발송된 개수를 가져온다.
    db_cursor.execute("select count(send_date) from send_history where send_date = '{0}'".format(current_date))
    records = db_cursor.fetchone()
    if records[0] > 10:
        # 하루동안 10개의 메일을 보내면 더 보내지 않게 한다.
        return False

    # 하루 10개도 안 보냈으면 메일을 보내도록 한다.
    db_cursor.execute("insert into send_history values ('{0}')".format(current_date))
    send_mail_db.commit()

    db_cursor.close()
    send_mail_db.close()

    return True
