import smtplib
import socket
from email.mime.text import MIMEText

from flask import request, render_template, Response, jsonify

from core import app, project_relative_location, config
import token_gen


@app.route('/')
def home():
    return render_template('home.html')


@app.route('/robots.txt')
def robots():
    return Response(open(project_relative_location('static/robots.txt')).read(), mimetype='text/plain')


@app.route('/email', methods=['GET', 'POST'])
def email():
    if not config.is_correct():
        return jsonify({'status': 'error', 'message': 'Server not configured properly.'})

    if request.method == 'GET':
        return render_template('email-form.html')

    if request.method == 'POST':
        token = request.form['token']
        tokens = token_gen.possible_tokens(config.token)

        if token not in tokens:
            return jsonify({'status': 'error', 'message': 'Invalid token'})

        subject = request.form['subject']
        content = request.form['content']

        if subject is None or len(subject) == 0 or content is None or len(content) == 0:
            return jsonify({'status': 'error', 'message': 'Invalid input'})

        response = mail(subject, content)
        return jsonify(response)


def mail(subject, content):
    server = config.smtp_server
    me = config.sender
    you = config.recipient

    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = me
    msg['To'] = you

    try:
        conn = smtplib.SMTP(server)
        conn.set_debuglevel(True)
        conn.login(me, config.smtp_password)
        conn.sendmail(me, [you], msg.as_string())
        conn.quit()

        return {'status': 'success', 'message': 'successfully sent'}
    except socket.error as e:
        return {'status': 'error', 'message': 'Socket error with message: {}'.format(e.message)}
