from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from config import CONFIG
from create_db import User, Card

from hashlib import md5


engine = create_engine(CONFIG['DB_CONNECTION'])
dbsessionmaker = sessionmaker(bind=engine)
dbsession = dbsessionmaker()


def share(card, user_id):
    #tu bi lahko naredili nek autoincrement ampak i guess da hash unique idja tudi daje unique share_id, tega potem uporabljamo, da preverimo matche
    h = md5(str(card.id).encode("utf-8")).hexdigest()
    card.share_id = h

    # all users 
    users = dbsession.query(User).filter(User.id != user_id).all()
    for user in users:
        #skip če že ima ta card v db.
        existing = dbsession.query(Card).filter(Card.title == card.title, Card.owner_id==user.id).all()
        if existing == []:
            print("sharing to, ", user.id)
            new_card = card = Card(title=card.title, interest_rate=-1.0, owner_id=user.id, item_location=card.item_location, last_review=None, share_id=h)
            dbsession.add(new_card)
            dbsession.commit()