from flask import Blueprint, request, current_app as app

from twoxy.blueprints.base import TemplateView
from twoxy.database.models import Blacklisted
from twoxy.database import db_ctx as db
from twoxy.util import ratelimit, random_twitter_auth, is_tweet_allowed

import json
import datetime
import twitter

blueprint = Blueprint("main", __name__)

class MainView(TemplateView):
    template_name = "main/index.html"
    title = "Post Tweets Anonymously"
    methods = ["GET", "POST"]

    def get_context_data(self, *args, **kwargs):
        context = super(MainView, self).get_context_data(*args, **kwargs)
        if request.method == "POST":
            if ratelimit.reached(app.config["POST_TWEET_HOURLY_LIMIT"], 60*60):
                 context["error"] = "You have reached the rate limit must wait before posting more tweets."
                 return context

            tweet = request.form.get("tweet", None)
            allowed, err = is_tweet_allowed(tweet)
            if not allowed:
                context["error"] = err
                return context

            auth = random_twitter_auth()
            if auth is None:
                context["error"] = "Could not obtain a Twitter authorization. Please try again later."
                return context

            api = twitter.Api(consumer_key=app.config["TWITTER_OAUTH_KEY"],
                  consumer_secret=app.config["TWITTER_OAUTH_SECRET"],
                  access_token_key=auth.oauth_token,
                  access_token_secret=auth.oauth_token_secret)

            image = request.files["image"] if "image" in request.files else None
            if image is not None:
                image.mode = "rb"
            try:
                status = api.PostUpdate(tweet, image)
                context["tweet"] = "https://twitter.com/{}/status/{}".format(status.user.name, status.id)
            except twitter.TwitterError as e:
                context["error"] = e.message[0]["message"]
                return context
        return context

class OptOutHandleView(TemplateView):
    template_name = "main/opt-out.html"
    title = "Opt-out"
    methods = ["GET", "POST"]

    def get_context_data(self, *args, **kwargs):
        context = super(OptOutHandleView, self).get_context_data(*args, **kwargs)
        if request.method == "POST":
            if not app.config["INDEX_POSTING_ENABLED"]:
                context["error"] = "Posting Tweets from the site index is currently disabled."
                return context

            if ratelimit.reached(app.config["OPT_OUT_HOURLY_LIMIT"], 60*60):
                context["error"] = "You have opted out too many handles and need to wait to submit more."
                return context

            handle = request.form.get("handle").lower()
            if handle[:1] == "@":
                handle = handle[1:]

            if len(handle) > 15:
                context["error"] = "The handle you specified is too long."
            elif Blacklisted.query.filter_by(handle=handle).first():
                context["error"] = "The handle you specified is already blacklisted."
            else:
                context["message"] = "The handle you specified is now opted-out."
                db.session.add(Blacklisted(handle))
                db.session.commit()
        return context

blueprint.add_url_rule("/", view_func=MainView.as_view("main"))
blueprint.add_url_rule("/opt-out", view_func=OptOutHandleView.as_view("opt-out"))

