def delete_ad(ad_id, user_id):
    try:
        with db.connect() as conn:
            conn.execute("DELETE FROM ads WHERE id=" + str(ad_id) + " AND user_id=" + str(user_id))
            return True
    except:
        error_client.report_exception()
        return False
def add_api_key(user_id):
    try:
        key = Utils.generate_key()
        command = sqlalchemy.text("INSERT INTO api_keys(user_id, api_key) VALUES(:user_id, :api_key)")
        with db.connect() as conn:
            conn.execute(command, user_id=user_id, api_key=key)
            return key
    except:
        error_client.report_exception()
        return ""
def update_ad_status(ad_id, status, user_id):
    try:
        if status:
            status = 1
        else:
            status = 0
        with db.connect() as conn:
            conn.execute("UPDATE ads SET status=" + str(status) + " Where id=" + str(ad_id) + " AND user_id=" + str(user_id))
            return True
    except:
        error_client.report_exception()
        return False
def get_user_of_key(api_key):
    try:
        command = sqlalchemy.text("SELECT user_id from api_keys WHERE api_key=:api_key")
        with db.connect() as conn:
            rows = conn.execute(command, api_key=api_key)
            if rows.rowcount == 0:
                return 0
            else:
                row = rows.fetchone()
                return int(row[0])
    except:
        error_client.report_exception()
        return 0
def get_api_key(user_id):
    try:
        command = sqlalchemy.text("SELECT api_key from api_keys WHERE user_id=:user_id")
        with db.connect() as conn:
            rows = conn.execute(command, user_id=user_id)
            if rows.rowcount == 0:
                return ""
            else:
                row = rows.fetchone()
                return row[0]
    except:
        error_client.report_exception()
        return ""
def get_user_by_phone(phone):
    try:
        command = sqlalchemy.text("SELECT id, email, password, phone_number, name, latitude, longitude"
                                  ", date_joined, confirmed, trial "
                                  " from users WHERE phone_number=:phone")
        with db.connect() as conn:
            rows = conn.execute(command, phone=phone)
            if rows.rowcount == 0:
                return None
            else:
                row = rows.fetchone()
                user = {'id': row[0], 'email': row[1], 'password': row[2], 'phone_number': row[3],
                        'name': row[4], 'latitude': row[5], 'longitude': row[6], 'date_joined': row[7],
                        'confirmed': row[8], 'trial': row[9]}
                return user
    except:
        error_client.report_exception()
        return None