# Copyright (c) 2015 iXsystems, Inc.
# All rights reserved.
# This file is a part of TrueNAS
# and may not be copied and/or distributed
# without the express permission of iXsystems.

import re

from django.http import HttpResponse
from django.shortcuts import render
from django.utils.translation import ugettext as _

from freenasUI.freeadmin.views import JsonResp
from freenasUI.middleware.client import client


def enclosure_status(request):
    with client as c:
        return render(request, "storage/enclosure_status.html", {
            'enclosures': c.call("enclosure.query"),
            'sensors': [
                sensor
                for sensor in c.call("sensor.query")
                if re.match(r'PS[0-9]+ Status', sensor['name'])
            ],
        })


def enclosure_identify_common(request, enc, slot, state):
    with client as c:
        try:
            c.call("enclosure.set_slot_status", enc, int(slot), state.upper())
        except Exception:
            return JsonResp(request, error=True, message=_("An error occurred."))

    if state == "identify" or state == "fault":
        return JsonResp(
            request,
            message=_("Slot %s has been successfully identified.") % slot
        )
    elif state == "clear":
        return JsonResp(
            request,
            message=_("Slot %s has been successfully cleared.") % slot
        )


def enclosure_identify(request, enc, slot):
    return enclosure_identify_common(request, enc, slot, "fault")


def enclosure_identify_clear(request, enc, slot):
    return enclosure_identify_common(request, enc, slot, "clear")


def enclosure_label(request):
    if request.method.lower() != 'post' or 'encid' not in request.POST:
        return HttpResponse()

    label = request.POST.get('label')

    with client as c:
        c.call('enclosure.update', request.POST.get('encid'), {'label': label})

    return JsonResp(
        request,
        message=label,
    )
