#!python
"""LICENSE
Copyright 2017 Hermann Krumrey <hermann@krumreyh.com>

This file is part of bundesliga-tippspiel.

bundesliga-tippspiel is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

bundesliga-tippspiel is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with bundesliga-tippspiel.  If not, see <http://www.gnu.org/licenses/>.
LICENSE"""

from flask import render_template
from bs4 import BeautifulSoup
from puffotter.smtp import send_email
from puffotter.env import load_env_file
from puffotter.flask.initialize import init_flask
from puffotter.flask.db.User import User
from puffotter.flask.db.TelegramChatId import TelegramChatId
from puffotter.flask.base import app
from bundesliga_tippspiel.Config import Config
from bundesliga_tippspiel import sentry_dsn, root_path
from bundesliga_tippspiel.db import models
from bundesliga_tippspiel.routes import blueprint_generators


def main():
    """
    Initializes and starts the flask application
    :return: None
    """
    load_env_file()
    init_flask(
        "bundesliga_tippspiel",
        sentry_dsn,
        root_path,
        Config,
        models,
        blueprint_generators
    )
    Config.initialize_telegram()

    with app.app_context():
        for user in User.query.all():

            message = render_template(
                "email/new_season.html",
                user=user
            )

            send_email(
                "hermann@krumreyh.com",
                f"Bundesliga Tippspiel Saison {Config.season_string()}",
                message,
                Config.SMTP_HOST,
                Config.SMTP_ADDRESS,
                Config.SMTP_PASSWORD,
                Config.SMTP_PORT
            )

            telegram = TelegramChatId.query.filter_by(user=user).first()
            if telegram is not None:
                message = BeautifulSoup(message, "html.parser").text
                message = "\n".join([x.strip() for x in message.split("\n")])
                telegram.send_message(message)


if __name__ == "__main__":
    main()
