# 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.

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

from freenasUI.freeadmin.views import JsonResp
from . import forms, models, ses


def enclosure_status(request):
    return render(request, "storage/enclosure_status.html", {
        'enclosures': ses.Enclosures(),
    })


def enclosure_identify_common(request, enc, slot, state):

    encs = ses.Enclosures()
    enc = encs.get_by_id(int(enc))
    ele = enc.get_by_slot(int(slot))
    if not ele.device_slot_set(state):
        return JsonResp(request, error=True, message=_("An error occurred."))
    elif 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')
    encl, created = models.EnclosureLabel.objects.get_or_create(
        encid=request.POST.get('encid')
    )
    encl.label = label
    encl.save()
    return JsonResp(
        request,
        message=label,
    )
