import requests
import json
import django

from datetime import datetime
from django.dispatch import receiver


from django.dispatch import receiver
from django.core import serializers
from django.utils import timezone


from dsmr_datalogger.models.reading import DsmrReading
from dsmr_pvoutput.models.settings import PVOutputAddStatusSettings
from dsmr_pvoutput.signals import pvoutput_upload


@receiver(django.db.models.signals.post_save, sender=DsmrReading)
def handle_dsmr_reading(sender, instance, created, raw, **kwargs):
    if not created or raw:
        return

    instance.timestamp = timezone.localtime(instance.timestamp)

    if instance.extra_device_timestamp:
        instance.extra_device_timestamp = timezone.localtime(instance.extra_device_timestamp)

    serialized = json.loads(serializers.serialize('json', [instance]))
    # {
    #   "timestamp": "2022-07-19T14:11:07.215912",
    #   "serialized": [
    #     {
    #       "model": "dsmr_datalogger.dsmrreading",
    #       "pk": 2577432,
    #       "fields": {
    #         "processed": false,
    #         "timestamp": "2022-07-19T14:11:11+02:00",
    #         "electricity_delivered_1": "5689.229",
    #         "electricity_returned_1": "366.707",
    #         "electricity_delivered_2": "5664.327",
    #         "electricity_returned_2": "688.836",
    #         "electricity_currently_delivered": "0.000",
    #         "electricity_currently_returned": "0.360",
    #         "phase_currently_delivered_l1": "0.000",
    #         "phase_currently_delivered_l2": null,
    #         "phase_currently_delivered_l3": null,
    #         "extra_device_timestamp": "2022-07-19T14:00:00+02:00",
    #         "extra_device_delivered": "3500.427",
    #         "phase_currently_returned_l1": "0.360",
    #         "phase_currently_returned_l2": null,
    #         "phase_currently_returned_l3": null,
    #         "phase_voltage_l1": null,
    #         "phase_voltage_l2": null,
    #         "phase_voltage_l3": null,
    #         "phase_power_current_l1": "2",
    #         "phase_power_current_l2": null,
    #         "phase_power_current_l3": null
    #       }
    #     }
    #   ]
    # }

    timestamp = datetime.today().isoformat()
    data = {
        'timestamp': timestamp,
        'model': serialized[0]['model'],
        'pk': serialized[0]['pk'],
        'fields': serialized[0]['fields']
    }
    path = f'/dump/{timestamp}-reading.json'
    json.dump(data, open(path, 'w'))

    # json_string = json.dumps(serialized[0]['fields'])
    # try:
    #     requests.post(
    #         'https://YOUR-DSMR-HOST/api/endpoint/',
    #         data=json_string,
    #         # A low timeout prevents DSMR-reader from hanging, when the remote server is unreachable.
    #         timeout=5
    #     )
    # except Exception as error:
    #     print('forward_json_dsmrreading_to_api:', error)


@receiver(pvoutput_upload)
def handle_pvoutput(**kwargs):
    # print(' - Uploading the same data to PVOutput using plugin: {}'.format(kwargs['data']))
    #  - Uploading the same data to PVOutput using plugin: {'d': '20220719', 't': '14:15', 'v3': 3817, 'v4': -366, 'n': 1}

    timestamp = datetime.today().isoformat()
    data = {
        'timestamp': timestamp,
        'data': kwargs['data']
    }
    path = f'/dump/{timestamp}-pvoutput.json'
    json.dump(data, open(path, 'w'))

    # response = requests.post(
    #     PVOutputAddStatusSettings.API_URL,
    #     headers={
    #         'X-Pvoutput-Apikey': 'XXXXX',
    #         'X-Pvoutput-SystemId': 'YYYYY',
    #     },
    #     data=kwargs['data']
    # )
    #
    # if response.status_code != 200:
    #     print(' [!] PVOutput upload failed (HTTP {}): {}'.format(response.status_code, response.text))
