# Path: admin/base/utils.py
# def change_embargo_date(registration, user, end_date):
#     """Update the embargo period of a registration
#     :param registration: Registration that is being updated
#     :param user: osf_admin that is updating a registration
#     :param end_date: Date when the registration should be made public
#     """
# 
#     validate_embargo_date(registration, user, end_date)
# 
#     if registration.embargo:
#         registration.embargo.end_date = end_date
#     else:
#         registration._initiate_embargo(
#             user,
#             end_date,
#             for_existing_registration=True,
#             notify_initiator_on_complete=False
#         )
# 
#     registration.is_public = False
# 
#     registration.embargo.save()
#     registration.save()
# 
#     update_admin_log(
#         user_id=user.id,
#         object_id=registration.id,
#         object_repr='Registration',
#         message='User {} changed the embargo end date of {} to {}.'.format(
#             user.pk, registration.pk, end_date
#         ),
#         action_flag=EMBARGO_UPDATED
#     )
# 
# def validate_embargo_date(registration, user, end_date):
#     if not user.has_perm('osf.change_node'):
#         raise PermissionDenied('Only osf_admins may update a registration embargo.')
#     if end_date - registration.registered_date >= settings.EMBARGO_END_DATE_MAX:
#         raise ValidationError('Registrations can only be embargoed for up to four years.')
#     elif end_date < timezone.now():
#         raise ValidationError('Embargo end date must be in the future.')
# 
# Path: osf/models/admin_log_entry.py
# def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN):
#     AdminLogEntry.objects.log_action(
#         user_id=user_id,
#         content_type_id=None,
#         object_id=object_id,
#         object_repr=object_repr,
#         change_message=message,
#         action_flag=action_flag
#     )
# 
# NODE_REMOVED = 30
# 
# NODE_RESTORED = 31
# 
# CONTRIBUTOR_REMOVED = 32
# 
# CONFIRM_SPAM = 20
# 
# CONFIRM_HAM = 21
# 
# UNFLAG_SPAM = 22
# 
# REINDEX_SHARE = 50
# 
# REINDEX_ELASTIC = 51


import pytz
from datetime import datetime
from framework import status
from django.utils import timezone
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.urlresolvers import NoReverseMatch
from django.db.models import F, Case, When, IntegerField
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.http import HttpResponse
from django.views.generic import (
    View,
    FormView,
    ListView,
    TemplateView,
)
from django.shortcuts import redirect, reverse
from django.urls import reverse_lazy
from admin.base.utils import change_embargo_date, validate_embargo_date
from admin.base.views import GuidView
from admin.base.forms import GuidForm
from api.share.utils import update_share
from api.caching.tasks import update_storage_usage_cache
from osf.exceptions import NodeStateError
from osf.models import (
    OSFUser,
    NodeLog,
    AbstractNode,
    Registration,
    SpamStatus
)
from osf.models.admin_log_entry import (
    update_admin_log,
    NODE_REMOVED,
    NODE_RESTORED,
    CONTRIBUTOR_REMOVED,
    CONFIRM_SPAM,
    CONFIRM_HAM,
    UNFLAG_SPAM,
    REINDEX_SHARE,
    REINDEX_ELASTIC,
)
from website import settings, search
        from osf.management.commands.force_archive import archive, verify


class DoiBacklogListView(RegistrationListView):
    """ Allows authorized users to view a list of registrations that have not yet been assigned a doi.
    """

    def get_queryset(self):
        # Django template does not like attributes with underscores for some reason, so we annotate.
        return Registration.find_doi_backlog().annotate(guid=F('guids___id'))


class RegistrationUpdateEmbargoView(NodeMixin, View):
    """ Allows authorized users to update the embargo of a registration.
    """
    permission_required = ('osf.change_node')
    raise_exception = True

    def post(self, request, *args, **kwargs):
        validation_only = request.POST.get('validation_only', False) == 'True'
        end_date = request.POST.get('date')
        user = request.user
        registration = self.get_object()

        try:
            end_date = pytz.utc.localize(datetime.strptime(end_date, '%m/%d/%Y'))
        except ValueError:
            return HttpResponse('Please enter a valid date.', status=400)

        try:
            if validation_only:

# Path: admin/base/utils.py
# def change_embargo_date(registration, user, end_date):
#     """Update the embargo period of a registration
#     :param registration: Registration that is being updated
#     :param user: osf_admin that is updating a registration
#     :param end_date: Date when the registration should be made public
#     """
# 
#     validate_embargo_date(registration, user, end_date)
# 
#     if registration.embargo:
#         registration.embargo.end_date = end_date
#     else:
#         registration._initiate_embargo(
#             user,
#             end_date,
#             for_existing_registration=True,
#             notify_initiator_on_complete=False
#         )
# 
#     registration.is_public = False
# 
#     registration.embargo.save()
#     registration.save()
# 
#     update_admin_log(
#         user_id=user.id,
#         object_id=registration.id,
#         object_repr='Registration',
#         message='User {} changed the embargo end date of {} to {}.'.format(
#             user.pk, registration.pk, end_date
#         ),
#         action_flag=EMBARGO_UPDATED
#     )
# 
# def validate_embargo_date(registration, user, end_date):
#     if not user.has_perm('osf.change_node'):
#         raise PermissionDenied('Only osf_admins may update a registration embargo.')
#     if end_date - registration.registered_date >= settings.EMBARGO_END_DATE_MAX:
#         raise ValidationError('Registrations can only be embargoed for up to four years.')
#     elif end_date < timezone.now():
#         raise ValidationError('Embargo end date must be in the future.')
# 
# Path: osf/models/admin_log_entry.py
# def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN):
#     AdminLogEntry.objects.log_action(
#         user_id=user_id,
#         content_type_id=None,
#         object_id=object_id,
#         object_repr=object_repr,
#         change_message=message,
#         action_flag=action_flag
#     )
# 
# NODE_REMOVED = 30
# 
# NODE_RESTORED = 31
# 
# CONTRIBUTOR_REMOVED = 32
# 
# CONFIRM_SPAM = 20
# 
# CONFIRM_HAM = 21
# 
# UNFLAG_SPAM = 22
# 
# REINDEX_SHARE = 50
# 
# REINDEX_ELASTIC = 51


# Path: admin/nodes/views.py
import pytz
from datetime import datetime
from framework import status
from django.utils import timezone
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.urlresolvers import NoReverseMatch
from django.db.models import F, Case, When, IntegerField
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.http import HttpResponse
from django.views.generic import (
    View,
    FormView,
    ListView,
    TemplateView,
)
from django.shortcuts import redirect, reverse
from django.urls import reverse_lazy
from admin.base.utils import change_embargo_date, validate_embargo_date
from admin.base.views import GuidView
from admin.base.forms import GuidForm
from api.share.utils import update_share
from api.caching.tasks import update_storage_usage_cache
from osf.exceptions import NodeStateError
from osf.models import (
    OSFUser,
    NodeLog,
    AbstractNode,
    Registration,
    SpamStatus
)
from osf.models.admin_log_entry import (
    update_admin_log,
    NODE_REMOVED,
    NODE_RESTORED,
    CONTRIBUTOR_REMOVED,
    CONFIRM_SPAM,
    CONFIRM_HAM,
    UNFLAG_SPAM,
    REINDEX_SHARE,
    REINDEX_ELASTIC,
)
from website import settings, search
        from osf.management.commands.force_archive import archive, verify



class DoiBacklogListView(RegistrationListView):
    """ Allows authorized users to view a list of registrations that have not yet been assigned a doi.
    """

    def get_queryset(self):
        # Django template does not like attributes with underscores for some reason, so we annotate.
        return Registration.find_doi_backlog().annotate(guid=F('guids___id'))


class RegistrationUpdateEmbargoView(NodeMixin, View):
    """ Allows authorized users to update the embargo of a registration.
    """
    permission_required = ('osf.change_node')
    raise_exception = True

    def post(self, request, *args, **kwargs):
        validation_only = request.POST.get('validation_only', False) == 'True'
        end_date = request.POST.get('date')
        user = request.user
        registration = self.get_object()

        try:
            end_date = pytz.utc.localize(datetime.strptime(end_date, '%m/%d/%Y'))
        except ValueError:
            return HttpResponse('Please enter a valid date.', status=400)

        try:
            if validation_only:

                validate_embargo_date(registration, user, end_date)