package com.atlassian.stash.internal.comment;

import com.atlassian.stash.internal.AbstractHibernateDao;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Arrays;

import static com.atlassian.stash.internal.HibernateUtils.initialize;

/**
 * A Hibernate-based implementation of {@link CommentDao}.
 */
@Repository("commentDao")
public class HibernateCommentDao extends AbstractHibernateDao<Long, InternalComment> implements CommentDao {

    @Autowired
    public HibernateCommentDao(SessionFactory sessionFactory) {
        super(sessionFactory);
    }

    @Override
    public InternalComment create(InternalComment entity) {
        InternalComment created = super.create(entity);

        //Note: We don't need to chase pointers to the root comment, only to the parent
        InternalComment parent = created.getParent();
        if (parent != null) {
            parent.addComment(created);
            session().update(parent);
        }

        return created;
    }

    @Override
    public void delete(InternalComment entity) {
        //Note: We don't need to chase pointers to the root comment, only to the parent
        InternalComment parent = entity.getParent();
        if (parent != null) {
            parent.removeComment(entity);
            session().update(parent);
        }

        super.delete(entity);
    }

    @Override
    public InternalComment getById(Long id) {
        return initialize(super.getById(id));
    }

    @Override
    public InternalComment update(InternalComment entity) {
        return initialize(super.update(entity));
    }

    @Override
    protected Iterable<Order> getImplicitOrder() {
        return Arrays.asList(Order.asc("createdDate"), Order.asc("id"));
    }
}
