from requests import get, ConnectionError, Timeout

from django.db import transaction
from django.conf import settings
from django.core.management.base import BaseCommand

from intranet.femida.src.vacancies import choices
from intranet.femida.src.vacancies.models import SubmissionForm


class Command(BaseCommand):

    help = 'Copy titles and description from Bunker to internal vacancies'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.updated = []
        self.errors = []

    def add_arguments(self, parser):
        parser.add_argument('--dry-run', action='store_true')

    @transaction.atomic
    def handle(self, *args, **options):
        for form in SubmissionForm.objects.all():
            self._handle_form(form, **options)

        if self.updated:
            print('Updated: ', self.updated)
        else:
            print('No vacancies updated')

        if self.errors:
            print('Errors: ', self.errors)
        else:
            print('Finished with no errors')

    def _handle_form(self, form, **options):
        url = (
            'http://{host}/v1/cat/?node=/vacancies-www/vacancies{title}'
            .format(host=settings.BUNKER_HOST, title=form.title)
        )
        try:
            response = get(url)
        except (ConnectionError, Timeout):
            self.errors.append(
                'Submission form id {} - Bunker is not responding'
                .format(form.pk)
            )
        else:
            if response.status_code == 200:
                vacancies = (
                    form.vacancies
                    .exclude(status=choices.VACANCY_STATUSES.closed)
                    .exclude(is_hidden=True)
                    .filter(publication_title='', publication_content='')
                )
                parsed_json = response.json()
                for vacancy in vacancies:
                    self.updated.append(vacancy.id)
                    if not options['dry_run']:
                        vacancy.publication_title = parsed_json['title']
                        vacancy.publication_content = parsed_json['description']
                        vacancy.is_published = True
                        vacancy.save(
                            update_fields=[
                                'publication_title',
                                'publication_content',
                                'is_published',
                            ]
                        )
            else:
                self.errors.append(
                    'Submission form id {} - code {}'
                    .format(form.pk, response.status_code)
                )
