import json

from django.http import JsonResponse
from django.views.decorators.http import require_http_methods

from authentication import authenticator
from machine import machine_controller


@require_http_methods(['POST'])
@authenticator.RequireAuth
def GetAllMachineInfo(request):
  return JsonResponse({'machines': machine_controller.GetAllMachineInfo()})


@require_http_methods(['POST'])
@authenticator.RequireAuth
def AddMachine(request):
  reqJson = json.loads(request.body)
  return JsonResponse({
    'result': machine_controller.AddMachine(
        reqJson['name'], reqJson['user'], reqJson['host'], reqJson['auth_key']),
  })


@require_http_methods(['POST'])
@authenticator.RequireAuth
def UpdateMachine(request):
  reqJson = json.loads(request.body)
  return JsonResponse({
    'result': machine_controller.UpdateMachine(
        reqJson['name'], reqJson['user'], reqJson['host'], reqJson['auth_key']),
  })


@require_http_methods(['POST'])
@authenticator.RequireAuth
def DeleteMachine(request):
  reqJson = json.loads(request.body)
  machine_controller.DeleteMachine(reqJson['name'])
  return JsonResponse({'result': 'DONE'})


@require_http_methods(['POST'])
@authenticator.RequireAuth
def SessionListMachines(request):
  return JsonResponse({'result': machine_controller.ListMachines()})


@require_http_methods(['POST'])
@authenticator.RequireAuth
def SessionPathStat(request):
  reqJson = json.loads(request.body)
  session_name = reqJson['session_name']
  machine_name = reqJson.get('machine_name', None)
  path = reqJson.get('path', None)
  controller = machine_controller.SessionController(session_name)
  return JsonResponse(controller.PathStat(machine_name, path))
