# Path: hepdata/modules/email/utils.py
# def create_send_email_task(destination, subject, message, reply_to_address=None):
#     """
#     Schedules a task to send an email.
# 
#     :param destination:
#     :param subject:
#     :param message:
#     :param reply_to_address:
#     :return: send_email
#     """
# 
#     # this is required for some unknown reason due to an initialisation problem with celery.
#     if not current_app.config.get('TESTING', False):
#         create_celery_app(current_app)
#         print('Sending email to {0}'.format(destination))
#         send_email.delay(destination, subject, message, reply_to_address)
#     else:
#         print('Not sending email as TESTING=True; would have sent email to {0}:'.format(destination))
#         import re
#         clean = re.compile('(?s)<.*?>')
#         newlines = re.compile(r'(?ms)(\n(\s*)){2,}')
#         print(re.sub(newlines, '\n', re.sub(clean, '', message)))
# 
# Path: hepdata/modules/permissions/models.py
# class CoordinatorRequest(db.Model):
#     """Stores coordinators, any text sent originally, and their collaboration."""
#     id = db.Column(
#         db.Integer, primary_key=True,
#         nullable=False, autoincrement=True)
# 
#     user = db.Column(db.Integer, db.ForeignKey(User.id))
#     collaboration = db.Column(db.String(512))
#     message = db.Column(LargeBinaryString)
# 
#     approved = db.Column(db.Boolean, default=False)
#     in_queue = db.Column(db.Boolean, default=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_primary_submission_participants_for_record(publication_recid):
#     submission_participants = get_submission_participants_for_record(publication_recid, status="primary")
#     return submission_participants
# 
# 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()


import logging
from flask import current_app
from flask_login import current_user
from invenio_userprofiles import UserProfile
from hepdata.modules.email.utils import create_send_email_task
from hepdata.modules.records.subscribers.api import get_users_subscribed_to_record
from hepdata.modules.records.utils.common import get_record_by_id
from flask import render_template
from hepdata.modules.permissions.models import CoordinatorRequest
from hepdata.modules.submission.api import get_latest_hepsubmission, \
    get_primary_submission_participants_for_record, get_submission_participants_for_record
from hepdata.modules.submission.models import HEPSubmission, DataSubmission, DataReview
from hepdata.utils.users import get_user_from_id
from invenio_accounts.models import User
from invenio_db import db
from sqlalchemy import and_
                                   collaboration=collaboration,
                                   article=recid,
                                   version=version,
                                   message=message,
                                   title=record['title'],
                                   site_url=site_url,
                                   link=site_url + "/record/{0}".format(recid),
                                   dashboard_link=site_url + "/dashboard"
                                   )

    create_send_email_task(coordinator.email,
                           '[HEPData] Submission {0} is ready to be finalised'.format(recid),
                           message_body,
                           reply_to_address=user.email)


def send_finalised_email(hepsubmission):

    record = get_record_by_id(hepsubmission.publication_recid)

    notify_participants(hepsubmission, record)
    notify_subscribers(hepsubmission, record)


def notify_participants(hepsubmission, record):

    destinations = []
    coordinator = User.query.get(hepsubmission.coordinator)
    if coordinator.id > 1:
        destinations.append(coordinator.email)

# Path: hepdata/modules/email/utils.py
# def create_send_email_task(destination, subject, message, reply_to_address=None):
#     """
#     Schedules a task to send an email.
# 
#     :param destination:
#     :param subject:
#     :param message:
#     :param reply_to_address:
#     :return: send_email
#     """
# 
#     # this is required for some unknown reason due to an initialisation problem with celery.
#     if not current_app.config.get('TESTING', False):
#         create_celery_app(current_app)
#         print('Sending email to {0}'.format(destination))
#         send_email.delay(destination, subject, message, reply_to_address)
#     else:
#         print('Not sending email as TESTING=True; would have sent email to {0}:'.format(destination))
#         import re
#         clean = re.compile('(?s)<.*?>')
#         newlines = re.compile(r'(?ms)(\n(\s*)){2,}')
#         print(re.sub(newlines, '\n', re.sub(clean, '', message)))
# 
# Path: hepdata/modules/permissions/models.py
# class CoordinatorRequest(db.Model):
#     """Stores coordinators, any text sent originally, and their collaboration."""
#     id = db.Column(
#         db.Integer, primary_key=True,
#         nullable=False, autoincrement=True)
# 
#     user = db.Column(db.Integer, db.ForeignKey(User.id))
#     collaboration = db.Column(db.String(512))
#     message = db.Column(LargeBinaryString)
# 
#     approved = db.Column(db.Boolean, default=False)
#     in_queue = db.Column(db.Boolean, default=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_primary_submission_participants_for_record(publication_recid):
#     submission_participants = get_submission_participants_for_record(publication_recid, status="primary")
#     return submission_participants
# 
# 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/email/api.py
import logging
from flask import current_app
from flask_login import current_user
from invenio_userprofiles import UserProfile
from hepdata.modules.email.utils import create_send_email_task
from hepdata.modules.records.subscribers.api import get_users_subscribed_to_record
from hepdata.modules.records.utils.common import get_record_by_id
from flask import render_template
from hepdata.modules.permissions.models import CoordinatorRequest
from hepdata.modules.submission.api import get_latest_hepsubmission, \
    get_primary_submission_participants_for_record, get_submission_participants_for_record
from hepdata.modules.submission.models import HEPSubmission, DataSubmission, DataReview
from hepdata.utils.users import get_user_from_id
from invenio_accounts.models import User
from invenio_db import db
from sqlalchemy import and_

                                   collaboration=collaboration,
                                   article=recid,
                                   version=version,
                                   message=message,
                                   title=record['title'],
                                   site_url=site_url,
                                   link=site_url + "/record/{0}".format(recid),
                                   dashboard_link=site_url + "/dashboard"
                                   )

    create_send_email_task(coordinator.email,
                           '[HEPData] Submission {0} is ready to be finalised'.format(recid),
                           message_body,
                           reply_to_address=user.email)


def send_finalised_email(hepsubmission):

    record = get_record_by_id(hepsubmission.publication_recid)

    notify_participants(hepsubmission, record)
    notify_subscribers(hepsubmission, record)


def notify_participants(hepsubmission, record):

    destinations = []
    coordinator = User.query.get(hepsubmission.coordinator)
    if coordinator.id > 1:
        destinations.append(coordinator.email)

    submission_participants = get_primary_submission_participants_for_record(hepsubmission.publication_recid)