# -*- coding: utf-8 -*-
from __future__ import annotations

from django.contrib import messages
from django.http import HttpResponse
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views.generic import FormView

from hotpocket_backend.apps.accounts.mixins import AccountRequiredMixin
from hotpocket_backend.apps.core.conf import settings
from hotpocket_backend.apps.ui.forms.imports import PocketImportForm
from hotpocket_backend.apps.ui.services import UIImportsService


class PocketImportView(AccountRequiredMixin, FormView):
    template_name = 'ui/imports/pocket.html'
    form_class = PocketImportForm

    def form_valid(self, form: PocketImportForm) -> HttpResponse:
        csv_filename = '{user_pk}-{filename}'.format(
            user_pk=self.request.user.pk,
            filename=form.cleaned_data['csv'].name,
        )

        csv_path = settings.UPLOADS_PATH / csv_filename
        with open(csv_path, 'wb') as csv_file:
            for chunk in form.cleaned_data['csv']:
                csv_file.write(chunk)

        result = UIImportsService().schedule_import_from_pocket(
            account_uuid=self.request.user.pk,
            csv_path=str(csv_path),
        )

        if result.ready() is True:
            messages.add_message(
                self.request,
                messages.SUCCESS,
                _('Import complete!'),
            )
        else:
            messages.add_message(
                self.request,
                messages.INFO,
                _('The import has been scheduled.'),
            )

        return super().form_valid(form)

    def get_success_url(self) -> str:
        return reverse('ui.associations.index')
