import json
from django.contrib.auth import get_user_model
from routeros_api.exceptions import RouterOsApiConnectionError

# from synology_api.exceptions import JSONDecodeError
User = get_user_model()
import os, requests,re
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from .logout import logout_view
from upanel.models import *
import routeros_api
import datetime


@login_required(login_url='/login/')
def connect(request):
    try:
        hosts = User.objects.values('ipaddress').distinct()[0]
        connection = routeros_api.RouterOsApiPool(hosts['ipaddress'], username='api', password='cbvgcjy0',
                                                  plaintext_login=True)
        api = connection.get_api()
        ping=api.get_binary_resource('/').call('ping', {'address': str.encode(hosts['ipaddress']), 'count': b'2'}) #блять тут надо перевести в байт str.encode
        return JsonResponse({'ethernet': bytes.decode(max([i['time'] for i in ping]))})
    except RouterOsApiConnectionError as e:
        return JsonResponse({'ethernet': 'false'})


# def server_smart(request):
#     month_int = sorted([int(datetime.datetime.now().strftime('%m'))-i for i in range(6)])
#     pattern = r'\+\d{2}+\.\d+'
#     return JsonResponse({'month':list(Month.objects.using('miroca').filter(id__in=month_int).order_by('id').values_list('name', flat=True)),
#                          'smart_server_temp':max(map(float,re.findall(pattern, os.popen('sensors').read())))})


# # @login_required(login_url='/login/')
# # @logout_view
# def greenhouse(request):
#     connect_timeout = 18
#     read_timeout = 30
#     host_name_green = Hostname.objects.values('area')[0]['area']
#     try:
#         response = requests.get("http://" + host_name_green, timeout=(connect_timeout, read_timeout))
#         return JsonResponse(response.json() | {'host_name_green':host_name_green})
#     except Exception as e:
#         return JsonResponse({'temp': [' ', ' '], 'sensor_lend_web': [' '], 'host_name_green':host_name_green})


@login_required(login_url='/login/')
@logout_view
def home(request):
    user = User.objects.get(id=request.user.id)
    return render(request, 'upanel/upanel/index.html',# {'user': user, 'temp': res['temp'][0], 'damp': res['sensor_lend_web'][0]}
     )

