# 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.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.truenas.mixins import AlertPlugins, Disk, Vol
from freenasUI.truenas.notifier import TNNotifier

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


class TrueNASHook(AppHook):

    name = 'truenas'

    def base_js(self, request):
        return []

    def hook_app_index_freeadmin(self, request):
        if os.path.exists(EULA_FILE):
            with open(EULA_FILE, 'r') as f:
                eula = f.read()

            if (
                os.path.exists('/data/truenas_license.pending') and
                'noeula' not in request.GET
            ):

                if request.POST.get('eula') == 'accept':
                    os.unlink('/data/truenas_license.pending')
                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_datagrid_buttons_VolumeFAdmin(self, admin):
        return [
            {
                'name': 'Enclosure',
                'verbose_name': _('View Enclosure'),
                'onclick': "viewModel('%s', '%s');" % (
                    escapejs(_('View Enclosure')),
                    reverse('storage_enclosure_status'),
                ),
            },
        ]

    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 = vars(Disk)
        myattrs['disk_enclosure_slot'] = models.IntegerField(
            verbose_name=_("Enclosure Slot"),
            blank=True,
            null=True,
            editable=False,
        )
        myattrs.pop('__module__', None)
        attrs.update(myattrs)

    def hook_model_new_Volume(self, bases, attrs):
        myattrs = vars(Vol)
        myattrs.pop('__module__', 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 []
