from connect import connect
from flask import jsonify
from flask_jwt_extended import create_access_token
from datetime import timedelta

conn = connect()
class RestFunc:
    def query_select(self, query, args=(), one=False):
        try:
            with conn.cursor() as cursor:
                cursor.execute(query, args)
                r = [dict((cursor.description[i][0], value) \
                        for i, value in enumerate(row)) for row in cursor.fetchall()]
                return (r[0] if r else None) if one else r
        except Exception as ex:
            return jsonify({"msg":str(ex)})

    def query_insert(self, query, args=()):
        try:
            with conn.cursor() as cursor:
                cursor.execute(query, args)
                conn.commit()
                return cursor.fetchone()[0]
        except Exception as ex:
            return jsonify({"msg":str(ex)})

    def query_delete(self, query, args=()):
        try:
            with conn.cursor() as cursor:
                cursor.execute(query, args)
                if(cursor.rowcount != 0):
                    conn.commit()
                    return True
            return False
        except: 
            return False

    def query_update(self, query, args=()):
        try:
            with conn.cursor() as cursor:
                cursor.execute(query, args)
                if(cursor.rowcount != 0):
                    conn.commit()
                    return True
            return False
        except: 
            return False

    def query_proverka(self, query, args=()):
        try:
            with conn.cursor() as cursor:
                cursor.execute(query, args)
                if(cursor.rowcount > 0):
                    return True
            return False
        except: 
            return False

    def gen_token(self, id, minut):
        token = {"access_token" : create_access_token(identity=id, expires_delta=timedelta(minutes=minut))}
        return jsonify(token)