from django.views import generic
from . import forms
from . import constant
from . import models
from time import localtime, strftime

class HomeApplianceOperation(generic.ListView):
    model = models.ControllerLink
    context_object_name = 'links'
    template_name = 'website/home_appliance_operation.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        controllers = {}
        for target_link in context[self.context_object_name]:
            link_name = target_link.link_name
            controllers[link_name] = models.ControllerCommand.objects.filter(link__link_name=link_name)
        context['controllers'] = controllers

        return context

class PiCamera(generic.FormView):
    template_name = 'website/picamera.html'
    form_class = forms.PiCameraForm

    def form_valid(self, form):
        try:
            # get response
            response = form.get_image()
            # get context
            context = self.get_context_data(img_response=response['img'], img_scale=response['scale'])
        except:
            context = self.get_context_data()

        return self.render_to_response(context)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['img_src'] = kwargs.get('img_response', constant.NO_IMAGE_BASE64)
        context['img_scale'] = kwargs.get('img_scale', constant.NO_IMAGE_SCALE)
        context['get_image_time'] = strftime('%Y/%m/%d %H:%M:%S', localtime())

        return context
