import threading
import time

from django.conf import settings
from django.contrib import admin
from django.contrib import messages

from django_admin_listfilter_dropdown.filters import DropdownFilter
import httpx
from mastodon import Mastodon


from . import models


def run_in_thread(fn):
    def run(*k, **kw):
        t = threading.Thread(target=fn, args=k, kwargs=kw)
        t.start()
        return t
    return run


@admin.register(models.Person)
class AdminPerson(admin.ModelAdmin):
    list_per_page = 50
    list_display = (
        'name',
        'country',
        'is_actor',
        'is_director')
        'is_woman')
    search_fields = ('name',)
    list_filter = ('is_woman', 'is_actor', 'is_director', 'country')


@admin.register(models.Movie)
class AdminMovie(admin.ModelAdmin):
    list_per_page = 50
    list_display = (
        'name',
        'original_name',
        'year',
        'duration',
        'count')
    search_fields = ('name', 'original_name')
    filter_horizontal = ('directors',)
    list_filter = (
        'is_digital',
        ('directors__name', DropdownFilter),
        ('countries__name', DropdownFilter),
        ('year', DropdownFilter),
        )
    _is_new = False
    actions = ['published']

    def save_model(self, request, obj, form, change):
        self._is_new = obj.pk is None
        super().save_model(request, obj, form, change)
        return

    def save_related(self, request, form, formsets, change):
        obj = form.instance
        super().save_related(request, form, formsets, change)
        if self._is_new and obj.published:
            self._public(obj)
        return

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == 'directors':
            kwargs['queryset'] = models.Person.objects.filter(is_director=True)
        if db_field.name == 'actors':
            kwargs['queryset'] = models.Person.objects.filter(is_actor=True)
        return super().formfield_for_manytomany(db_field, request, **kwargs)

    def published(self, request, queryset):
        obj = queryset[0]
        self._public(obj)
        self.message_user(request, 'Publicado correctamente', messages.SUCCESS)
    published.short_description = 'Republicar en redes'

    def _public_mastodon(self, message, cartel):
        MT = {
            'jpg': 'image/jpeg',
            'png': 'image/png',
        }
        message += '\n\n#mauflix'
        media_type = MT[cartel.url[-3:]]

        try:
            server = Mastodon(
                access_token=settings.TOKEN_MASTODON,
                api_base_url=settings.URL_MASTODON)

            media = server.media_post(cartel.read(), media_type)
            server.status_post(message, media_ids=media)
        except Exception as e:
            print(str(e))
        return

    def _public_telegram(self, message, cartel):
        url = f'https://api.telegram.org/bot{settings.TOKEN_TELEGRAM}/sendPhoto'
        url_cartel = settings.URL_CDN.format(cartel)
        data = {'chat_id': settings.CHAT_ID, 'photo': url_cartel, 'caption': message}
        result = httpx.post(url, data=data).json()
        return

    @run_in_thread
    def _public(self, obj):
        time.sleep(3)
        message = f"""\"{obj.name}\"
Dir: {', '.join(obj.directors.values_list('name', flat=True))}
País: {', '.join(obj.countries.values_list('name', flat=True))}
Año: {obj.year}
"""
        self._public_mastodon(message, obj.cartel)
        self._public_telegram(message, obj.cartel.url)
        return


admin.site.register(models.Gender)
admin.site.register(models.Country)

