# Path: hepdata/modules/permissions/models.py
# class SubmissionParticipant(db.Model):
# 
#     """
#     This table stores information about the reviewers and
#     uploaders of a HEPData submission.
#     """
#     __tablename__ = "submissionparticipant"
# 
#     id = db.Column(db.Integer, primary_key=True,
#                    nullable=False, autoincrement=True)
# 
#     publication_recid = db.Column(db.Integer)
# 
#     full_name = db.Column(db.String(128))
#     email = db.Column(db.String(128))
#     affiliation = db.Column(db.String(128))
#     invitation_cookie = db.Column(UUIDType, default=uuid.uuid4)
# 
#     # when the user logs in with their cookie,
#     # this user_account should be updated.
#     user_account = db.Column(db.Integer, db.ForeignKey(User.id))
# 
#     # e.g., reviewer or uploader
#     role = db.Column(db.String(32), default='')
#     # e.g. primary or reserve reviewer/uploader
#     status = db.Column(db.String(32), default='reserve')
#     action_date = db.Column(db.DateTime, default=datetime.utcnow, nullable=True, index=True)
# 
# Path: hepdata/modules/submission/api.py
# def get_latest_hepsubmission(*args, **kwargs):
#     """
#     Gets the latest HEPSubmission record matching the given kwargs
# 
#     :return: the HEPSubmission object or None
#     """
# 
#     hepsubmissions = HEPSubmission.query.filter_by(**kwargs).all()
# 
#     last = None
#     for hepsubmission in hepsubmissions:
#         if last is None:
#             last = hepsubmission
#         else:
#             if hepsubmission.version > last.version:
#                 last = hepsubmission
# 
#     return last
# 
# def get_submission_participants_for_record(publication_recid, roles=None, **kwargs):
#     """Gets the participants for a given publication record id
# 
#     :param int publication_recid: publication_recid of a submission.
#     :param ``**kwargs``: Additional filter parameters to pass to `filter_by`.
#     :return: List of participants relating to that record
#     :rtype: list[SubmissionParticipant]
#     """
#     query = SubmissionParticipant.query.filter_by(
#             publication_recid=publication_recid,
#             **kwargs
#     )
# 
#     if roles:
#         query = query.filter(SubmissionParticipant.role.in_(roles))
# 
#     return query.all()
# 
# Path: hepdata/modules/records/utils/users.py
# def has_role(user, required_role):
#     """
#     Determines if a user has a particular role.
# 
#     :param user: a current_user object
#     :param required_role: e.g. 'admin'
#     :return: True if the user has the role, False otherwise
#     """
#     for role in user.roles:
#         if role.name == required_role:
#             return True
#     return False
# 
# Path: hepdata/utils/session.py
# def get_session_item(key):
#     return session.get(key, [])
# 
# def set_session_item(key, value):
#     """
#     Stores a key and value in the session.
#     By default we use REDIS.
# 
#     :param key: e.g. my_key
#     :param value: anything, dict, array, string, int, etc.
#     :return: 'ok'
#     """
#     session[key] = value
#     return 'ok'


from collections import OrderedDict
from invenio_accounts.models import User
from sqlalchemy import and_, or_, func
from hepdata.modules.permissions.models import SubmissionParticipant
from hepdata.modules.records.utils.common import get_record_by_id, decode_string
from hepdata.modules.submission.api import get_latest_hepsubmission, get_submission_participants_for_record
from hepdata.modules.records.utils.users import has_role
from hepdata.modules.submission.models import HEPSubmission, DataReview
from hepdata.utils.session import get_session_item, set_session_item
from hepdata.utils.users import get_user_from_id
    # The final rendering in the dashboard should be different
    # though considering the user him/herself is probably not a
    # reviewer/uploader
    if not has_role(user, 'admin'):
        # Not an admin user
        # We just want to pick out people with access to particular records,
        # i.e. submissions for which they are primary reviewers or coordinators.

        inner_query = SubmissionParticipant.query.filter_by(
            user_account=int(user.get_id()),
            status='primary'
        ).with_entities(
            SubmissionParticipant.publication_recid
        )

        query = query.filter(
            or_(HEPSubmission.coordinator == int(user.get_id()),
                HEPSubmission.publication_recid.in_(inner_query))
        )

    return query


def get_pending_invitations_for_user(user):
    """
    Returns pending invites for upload or review of records.

    :param user: User object
    :return: array of pending invites
    """

# Path: hepdata/modules/permissions/models.py
# class SubmissionParticipant(db.Model):
# 
#     """
#     This table stores information about the reviewers and
#     uploaders of a HEPData submission.
#     """
#     __tablename__ = "submissionparticipant"
# 
#     id = db.Column(db.Integer, primary_key=True,
#                    nullable=False, autoincrement=True)
# 
#     publication_recid = db.Column(db.Integer)
# 
#     full_name = db.Column(db.String(128))
#     email = db.Column(db.String(128))
#     affiliation = db.Column(db.String(128))
#     invitation_cookie = db.Column(UUIDType, default=uuid.uuid4)
# 
#     # when the user logs in with their cookie,
#     # this user_account should be updated.
#     user_account = db.Column(db.Integer, db.ForeignKey(User.id))
# 
#     # e.g., reviewer or uploader
#     role = db.Column(db.String(32), default='')
#     # e.g. primary or reserve reviewer/uploader
#     status = db.Column(db.String(32), default='reserve')
#     action_date = db.Column(db.DateTime, default=datetime.utcnow, nullable=True, index=True)
# 
# Path: hepdata/modules/submission/api.py
# def get_latest_hepsubmission(*args, **kwargs):
#     """
#     Gets the latest HEPSubmission record matching the given kwargs
# 
#     :return: the HEPSubmission object or None
#     """
# 
#     hepsubmissions = HEPSubmission.query.filter_by(**kwargs).all()
# 
#     last = None
#     for hepsubmission in hepsubmissions:
#         if last is None:
#             last = hepsubmission
#         else:
#             if hepsubmission.version > last.version:
#                 last = hepsubmission
# 
#     return last
# 
# def get_submission_participants_for_record(publication_recid, roles=None, **kwargs):
#     """Gets the participants for a given publication record id
# 
#     :param int publication_recid: publication_recid of a submission.
#     :param ``**kwargs``: Additional filter parameters to pass to `filter_by`.
#     :return: List of participants relating to that record
#     :rtype: list[SubmissionParticipant]
#     """
#     query = SubmissionParticipant.query.filter_by(
#             publication_recid=publication_recid,
#             **kwargs
#     )
# 
#     if roles:
#         query = query.filter(SubmissionParticipant.role.in_(roles))
# 
#     return query.all()
# 
# Path: hepdata/modules/records/utils/users.py
# def has_role(user, required_role):
#     """
#     Determines if a user has a particular role.
# 
#     :param user: a current_user object
#     :param required_role: e.g. 'admin'
#     :return: True if the user has the role, False otherwise
#     """
#     for role in user.roles:
#         if role.name == required_role:
#             return True
#     return False
# 
# Path: hepdata/utils/session.py
# def get_session_item(key):
#     return session.get(key, [])
# 
# def set_session_item(key, value):
#     """
#     Stores a key and value in the session.
#     By default we use REDIS.
# 
#     :param key: e.g. my_key
#     :param value: anything, dict, array, string, int, etc.
#     :return: 'ok'
#     """
#     session[key] = value
#     return 'ok'


# Path: hepdata/modules/dashboard/api.py
from collections import OrderedDict
from invenio_accounts.models import User
from sqlalchemy import and_, or_, func
from hepdata.modules.permissions.models import SubmissionParticipant
from hepdata.modules.records.utils.common import get_record_by_id, decode_string
from hepdata.modules.submission.api import get_latest_hepsubmission, get_submission_participants_for_record
from hepdata.modules.records.utils.users import has_role
from hepdata.modules.submission.models import HEPSubmission, DataReview
from hepdata.utils.session import get_session_item, set_session_item
from hepdata.utils.users import get_user_from_id

    # The final rendering in the dashboard should be different
    # though considering the user him/herself is probably not a
    # reviewer/uploader
    if not has_role(user, 'admin'):
        # Not an admin user
        # We just want to pick out people with access to particular records,
        # i.e. submissions for which they are primary reviewers or coordinators.

        inner_query = SubmissionParticipant.query.filter_by(
            user_account=int(user.get_id()),
            status='primary'
        ).with_entities(
            SubmissionParticipant.publication_recid
        )

        query = query.filter(
            or_(HEPSubmission.coordinator == int(user.get_id()),
                HEPSubmission.publication_recid.in_(inner_query))
        )

    return query


def get_pending_invitations_for_user(user):
    """
    Returns pending invites for upload or review of records.

    :param user: User object
    :return: array of pending invites
    """

    pending_invites = SubmissionParticipant.query.filter(