from django.utils import timezone
from django.db.models import Sum
from rest_framework import serializers
from counter.models import DeviceCount, DeviceInfo


class DeviceCountSerializer(serializers.ModelSerializer):
    mosq_count = serializers.SerializerMethodField()
    signal = serializers.SerializerMethodField()
    energy = serializers.SerializerMethodField()
    calc_time = serializers.SerializerMethodField()

    class Meta:
        model = DeviceCount
        fields = [
            'id',
            'device_id',
            'signal',
            'mosq_count',
            'energy',
            'calc_time',
            'longitude',
            'latitude'
        ]

    def get_mosq_count(self, obj):
        return obj.count

    def get_signal(self, obj):
        return obj.csq

    def get_energy(self, obj):
        return obj.vol

    def get_calc_time(self, obj):
        return obj.data_time.strftime('%Y-%m-%d %H:%M:%S')


class DeviceInfoSerializer(serializers.ModelSerializer):
    compile_time = serializers.SerializerMethodField()
    last_connect = serializers.SerializerMethodField()
    last_offline_time = serializers.SerializerMethodField()

    class Meta:
        model = DeviceInfo
        fields = [
            'device_id',
            'device_name',
            'chip_type',
            'chip_id',
            'compile_time',
            'online',
            'last_connect',
            'last_offline_time'
        ]

    def get_compile_time(self, obj):
        if obj.compile_time:
            return obj.compile_time.strftime('%Y-%m-%d %H:%M:%S')
        return None

    def get_last_connect(self, obj):
        if obj.last_connect:
            return obj.last_connect.strftime('%Y-%m-%d %H:%M:%S')
        return None

    def get_last_offline_time(self, obj):
        if obj.last_offline_time:
            return obj.last_offline_time.strftime('%Y-%m-%d %H:%M:%S')
        return None
