# 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.utils.translation import ugettext as _

from freenasUI.freeadmin.options import BaseFreeAdmin
from freenasUI.freeadmin.site import site

from . import models
from .resources import FailoverResource


class FailoverFAdmin(BaseFreeAdmin):

    exclude_fields = (
        'id',
        'secret',
    )
    icon_model = "FailoverIcon"
    menu_child_of = 'system'
    nav_extra = {
        'order': 500,
    }
    resource = FailoverResource

    def get_actions(self):
        actions = super(FailoverFAdmin, self).get_actions()
        actions['SyncFrom'] = {
            'button_name': _('Sync From Peer'),
            'on_click': """function() {
                var mybtn = this;
                for (var i in grid.selection) {
                    var data = grid.row(i).data;
                    editObject('Sync From Peer', data._syncfrom_url, [this,]);
                }
            }""",
        }

        actions['SyncTo'] = {
            'button_name': _('Sync To Peer'),
            'on_click': """function() {
                var mybtn = this;
                for (var i in grid.selection) {
                    var data = grid.row(i).data;
                    editObject('Sync To Peer', data._syncto_url, [this,]);
                }
            }""",
            'on_select_after': """function(evt, actionName, action) {
    var numrows = 0;
    for(var i in evt.grid.selection) numrows++;
    if(numrows != 1) {
        query(".grid" + actionName).forEach(function(item, idx) {
            domStyle.set(item, "display", "none");
        });
    } else {
        var row = evt.rows[0];
        if(row.data._syncto_url == undefined) {
            query(".grid" + actionName).forEach(function(item, idx) {
                domStyle.set(item, "display", "none");
            });
        }
    }

            }""",
        }

        return actions

    def get_datagrid_context(self, request):
        return {
            'has_failover': models.Failover.objects.all().exists(),
        }


site.register(models.Failover, FailoverFAdmin)
