import datetime
import tabulate
from FlaskApp import db
from models import User, Logins
from werkzeug.security import generate_password_hash
# , check_password_hash
from geolite2 import geolite2


class UserManager():
    def __init__(self):
        pass

    def toggle_admin(self, userid):
        user = db.session.query(User).filter_by(id=userid).first()
        print(dir(user))
        if user.admin:
            user.admin = False
        else:
            user.admin = True
        db.session.commit()

    def add_user(self, username, email, password, admin, phone):
        hashed_password = generate_password_hash(password, method='sha256')
        uc = db.session.query(User)
        uc = uc.filter_by(username=username)
        uc = uc.count()
        if uc:
            print("User %s exists" % username)
        else:
            print("Creating user %s" % username)
            new_user = User(
                username=username.lower(),
                email=email,
                password=hashed_password,
                admin=admin,
                phone=phone,
                created=datetime.datetime.now(),
                lastlogin=None)
            db.session.add(new_user)
            db.session.commit()

    def log_user_login(self, uid, username, ipa):
        db.session.query(User).filter_by(
            id=uid).update(
                dict(lastlogin=datetime.datetime.now()))
        db.session.commit()
        reader = geolite2.reader()
        d = reader.get(ipa)
        if d:
            loc = d['country']['names']['en']
        else:
            loc = "Lokalt netværk"
        nl = Logins(
            userid=uid,
            username=username,
            lastlogin=datetime.datetime.now(),
            ipaddress=ipa,
            location=loc)
        db.session.add(nl)
        db.session.commit()
        geolite2.close()

    def list_logins(self):
        ll = []
        logins = db.session.query(Logins).order_by("lastlogin desc")
        for login in logins:
            ll.append([
                login.loginid,
                login.userid,
                login.username,
                login.lastlogin.strftime("%Y-%m-%d %H:%M:%S"),
                login.ipaddress,
                login.location])
        return ll

    def delete_user(self, userid):
        db.session.query(User).filter_by(id=userid).delete()
        db.session.commit()

    def set_user_admin(self, userid, status):
        pass

    def list_users(self):
        userlist = []
        users = db.session.query(User).order_by("admin desc, username asc")
        for u in users:
            ll = "Aldrig"
            if u.lastlogin is not None:
                ll = u.lastlogin.strftime("%Y-%m-%d %H:%M:%S")
            print(ll)
            userlist.append([
                u.id,
                u.username,
                u.email,
                u.admin,
                u.phone,
                u.created.strftime("%Y-%m-%d %H:%M:%S"),
                ll])
        return userlist

    def print_users_list(self):
        h = ['ID', 'USERNAME', 'EMAIL', 'ADMIN', 'PHONE', 'CREATED']
        ul = self.list_users()
        print("Userlist:")
        print(tabulate.tabulate(ul, headers=h))

    def reset_password(self, uid, pw):
        db.session.query(User).filter_by(
            id=uid).update(
                dict(password=pw))
        db.session.commit()

    def reset_password_hashed(self, uid, pw):
        hashed_password = generate_password_hash(pw, method='sha256')

        db.session.query(User).filter_by(
            id=uid).update(
                dict(password=hashed_password))
        db.session.commit()


if __name__ == '__main__':
    print("Testing shit")
    o = UserManager()

    o.add_user(
        'jacob',
        'jacob@arpsorensen.dk',
        'BillStillSux',
        False,
        '00422841',
        40592903)
    o.add_user(
        'charlotte',
        'charlotte@arpsorensen.dk',
        'BillStillSux',
        False,
        '00422841',
        40592903)

    o.print_users_list()

    o.reset_password(5, 'testtesttest')
    o.reset_password(5, 'BillStillSux')

    # o.delete_user(5)
    # o.print_users_list()
