# -*- coding: utf-8 -*-

from django.conf import settings
from django.contrib import admin
from django.template.loader import render_to_string

from operation.models import FeedbackInfo, GuestEntranceControlInfo, LatestAppInfo, SplashInfo
from utils.disk_utils import write_to_disk
from utils.redis.rapp import set_latest_app
from utils.redis.rversion import delete_guest_entrance_control, set_guest_entrance_control


class LatestAppInfoAdmin(admin.ModelAdmin):
    list_display = ('latest_adr_version_code', 'latest_adr_version_name', 'latest_adr_app', 'latest_adr_url', 'latest_ios_version_code', 'latest_ios_version_name', 'latest_ios_url', 'status', 'created_at', 'updated_at')

    def save_model(self, request, obj, form, change):
        obj.save()

        # 更新安卓下载页面
        write_to_disk(render_to_string('page/download.tmpl.html', {
            'version': obj.latest_adr_version_name,
        }), settings.DOWNLOAD_ADR_PAGE_PATH)

        # 更新 iOS 下载页面
        write_to_disk(render_to_string('page/download.tmpl.html', {
            'version': obj.latest_ios_version_name,
        }), settings.DOWNLOAD_IOS_PAGE_PATH)

        # 设置最新 APP 信息
        set_latest_app()


class SplashInfoAdmin(admin.ModelAdmin):
    list_display = ('splash_image', 'spalash_image_airtime', 'spalash_image_deadline', 'status', 'created_at', 'updated_at')


class FeedbackInfoAdmin(admin.ModelAdmin):
    list_display = ('user_id', 'feedback', 'status', 'created_at', 'updated_at')


class GuestEntranceControlInfoAdmin(admin.ModelAdmin):
    list_display = ('platform', 'min_adr', 'max_adr', 'min_ios', 'max_ios', 'status', 'created_at', 'updated_at')

    def save_model(self, request, obj, form, change):
        obj.save()

        # 设置游客入口控制
        set_guest_entrance_control(obj)

    def delete_model(self, request, obj):
        obj.delete()

        # 删除游客入口控制
        delete_guest_entrance_control()


admin.site.register(LatestAppInfo, LatestAppInfoAdmin)
admin.site.register(SplashInfo, SplashInfoAdmin)
admin.site.register(FeedbackInfo, FeedbackInfoAdmin)
admin.site.register(GuestEntranceControlInfo, GuestEntranceControlInfoAdmin)
