# 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 logging
import os

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.utils.html import escapejs
from django.utils.translation import ugettext as _

from freenasUI.common.system import get_sw_name, get_sw_version
from freenasUI.freeadmin.hook import AppHook
from freenasUI.middleware.client import client
from freenasUI.truenas.mixins import AlertPlugins, Disk, Vol
from freenasUI.truenas.notifier import TNNotifier

EULA_FILE = '/usr/local/share/truenas/eula.html'
log = logging.getLogger('truenas.hook')


class TrueNASHook(AppHook):

    name = 'truenas'

    def base_js(self, request):
        return []

    def hook_app_index_freeadmin(self, request):
        if not request.session.get("noeula"):
            if os.path.exists(EULA_FILE):
                with open(EULA_FILE, 'r', encoding='utf8') as f:
                    eula = f.read()

                with client as c:
                    if not c.call('truenas.is_eula_accepted'):
                        if request.POST.get('eula') == 'accept':
                            c.call('truenas.accept_eula')
                            return HttpResponseRedirect("/")
                        elif request.POST.get('eula') == 'skip':
                            request.session['noeula'] = True
                            return HttpResponseRedirect("/")
                        else:
                            sw_version = get_sw_version()
                            return render(request, 'eula.html', {
                                'sw_name': get_sw_name(),
                                'sw_version': sw_version,
                                'eula': eula,
                            })

    def hook_class_new_notifier(self, bases, attrs):
        bases.insert(0, TNNotifier)

    def hook_class_new_AlertPlugins(self, bases, attrs):
        bases.insert(0, AlertPlugins)

    def hook_datagrid_actions_DiskFAdmin(self, admin, actions):
        actions['Identify'] = {
            'on_select_after': """function(evt, actionName, action) {
                for(var i=0;i < evt.rows.length;i++) {
                  var row = evt.rows[i];
                  if(row.data._identify_url == undefined) {
                    query(".grid" + actionName).forEach(function(item, idx) {
                      domStyle.set(item, "display", "none");
                    });
                    break;
                  }
                }
                }""",
            'button_name': _('Identify'),
            'on_click': """
                function() {
                  var b = this;
                  require([
                    "dojo/json",
                    "dojo/request/xhr"
                    ], function(
                    djson,
                    xhr
                    ) {
                    for (var i in grid.selection) {
                      var data = grid.row(i).data;
                      b.set('label', '%(wait)s');
                      b.set('disabled',true);
                      xhr.get(data._identify_url, {
                        handleAs: 'text'
                      }).then(function(data, ioArgs) {
                        try {
                          var json = djson.parse(data);
                          if(json.error == true) {
                            setMessage(json.message, "error");
                          } else {
                            setMessage(json.message);
                          }
                        } catch(e) {
                          console.log(e);
                        }
                        b.set('label', '%(identify_txt)s');
                        b.set('disabled', false);
                      });
                    }
                  });
                }""" % {
                'identify_txt': escapejs(_("Identify")),
                'wait': escapejs(_("Please wait...")),
            },
        }

        actions['IdentifyClear'] = {
            'on_select_after': """function(evt, actionName, action) {
                for(var i=0;i < evt.rows.length;i++) {
                  var row = evt.rows[i];
                  if(row.data._identify_clear_url == undefined) {
                    query(".grid" + actionName).forEach(function(item, idx) {
                      domStyle.set(item, "display", "none");
                    });
                    break;
                  }
                }
            }""",
            'button_name': _('Reset LED'),
            'on_click': """
              function() {
                var b = this;
                require([
                  "dojo/json",
                  "dojo/request/xhr"
                  ], function(
                  djson,
                  xhr
                  ) {
                  for (var i in grid.selection) {
                    var data = grid.row(i).data;
                    b.set('label', '%(wait)s');
                    b.set('disabled',true);
                    xhr.get(data._identify_clear_url, {
                      handleAs: 'text'
                    }).then(function(data, ioArgs) {
                      try {
                        var json = djson.parse(data);
                        if(json.error == true) {
                          setMessage(json.message, "error");
                        } else {
                          setMessage(json.message);
                        }
                      } catch(e) {
                        console.log(e);
                      }
                      b.set('label', '%(reset_txt)s');
                      b.set('disabled', false);
                    });
                  }
                });
            }""" % {
                'reset_txt': escapejs(_("Reset LED")),
                'wait': escapejs(_("Please wait...")),
            },
        }

    def hook_form_init_AdvancedForm(self, form, *args, **kwargs):
        from dojango import forms
        form.fields['adv_swapondrive'].widget = forms.widgets.HiddenInput()

    def hook_model_new_Disk(self, bases, attrs):
        from django.db import models
        myattrs = dict(vars(Disk))
        myattrs.pop('__module__', None)
        myattrs.pop('__dict__', None)
        attrs.update(myattrs)

    def hook_model_new_Volume(self, bases, attrs):
        myattrs = dict(vars(Vol))
        myattrs.pop('__module__', None)
        myattrs.pop('__dict__', None)
        attrs.update(myattrs)

    def hook_resource_bundle_DiskResource(self, resource, bundle):
        from freenasUI.middleware.notifier import notifier
        if not hasattr(notifier, 'get_enc_slot_from_dev'):
            return
        enc_slot = notifier().get_enc_slot_from_dev(bundle.obj.disk_name)
        if enc_slot:
            bundle.data['_identify_url'] = reverse(
                'storage_enclosure_identify',
                kwargs={
                    'enc': enc_slot[0],
                    'slot': enc_slot[1],
                })
            bundle.data['_identify_clear_url'] = reverse(
                'storage_enclosure_identify_clear',
                kwargs={'enc': enc_slot[0], 'slot': enc_slot[1]})

    def hook_view_context(self, name, *args, **kwargs):
        return []
