import argparse
from datetime import datetime

from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.db import transaction

from docbow_project.docbow.models import Document, Inbox
from docbow_project.docbow.utils import date_to_aware_datetime


def valid_date(s):
    try:
        return date_to_aware_datetime(datetime.strptime(s, '%Y-%m-%d'))
    except ValueError:
        msg = "Not a valid date: '{0}'.".format(s)
        raise argparse.ArgumentTypeError(msg)


class Command(BaseCommand):
    help = 'Forward documents received by a user to another'

    def add_arguments(self, parser):
        parser.add_argument('from_user', type=int)
        parser.add_argument('to_user', type=int)
        parser.add_argument(
            '-s', '--startdate', required=False, type=valid_date, help='The start date - format YYYY-MM-DD'
        )
        parser.add_argument(
            '-e', '--enddate', required=False, type=valid_date, help='The end date - format YYYY-MM-DD'
        )

    @transaction.atomic
    def handle(self, from_user, to_user, *args, **kwargs):
        verbose = kwargs.get('verbosity') > 1

        from_user = User.objects.get(pk=from_user)
        to_user = User.objects.get(pk=to_user)
        from_user_inboxes = Inbox.objects.filter(owner=from_user, outbox=False)
        to_user_inboxes = Inbox.objects.filter(owner=to_user, outbox=False)
        docs = (
            Document.objects.exclude(deleteddocument__user=from_user)
            .filter(mailboxes__in=from_user_inboxes)
            .exclude(mailboxes__in=to_user_inboxes)
            .distinct()
        )

        startdate, enddate = kwargs.get('startdate'), kwargs.get('enddate')
        if startdate:
            docs = docs.filter(date__gte=startdate)
        if enddate:
            docs = docs.filter(date__lt=enddate)

        if verbose:
            print('Prepare forwarding', docs.count(), 'from', from_user, 'to', to_user)
        for doc in docs:
            doc.forward(doc.sender, [], [to_user])
            if verbose:
                print('Forward ', doc)
