
require([
  "dojo/_base/lang",
  "dojo/cookie",
  "dojo/dom",
  "dojo/dom-class",
  "dojo/dom-style",
  "dojo/ready",
  "dojo/request/xhr",
  "dijit/Dialog",
  "dijit/_base/manager",
  "dijit/registry"
], function(
  lang,
  cookie,
  dom,
  domClass,
  domStyle,
  ready,
  xhr,
  Dialog,
  manager,
  registry
) {

    checkFailoverStatus = function () {

        var refreshFailover = function() {
            window.location = '/';
        }

        xhr.get('/failover/status/', {
            preventCache: true
        }).then(function(data) {
            var menuitem = dom.byId("failover_menuitem");
            var statusitem = dom.byId("failover_status");
            var statusname = dom.byId("failover_status_name");
            domStyle.set(menuitem, "display", "inherit");
            statusname.status = data;
            if(data == 'MASTER') {
                statusname.innerHTML = 'Active';
                if(
                  domClass.contains(statusitem, "failover_electing") ||
                  domClass.contains(statusitem, "failover_importing") ||
                  domClass.contains(statusitem, "failover_passive") ||
                  domClass.contains(statusitem, "failover_error")
                  ) {
                    domClass.remove(statusitem, ["failover_electing", "failover_importing", "failover_passive", "failover_error"]);
                    domClass.add(statusitem, "failover_ok");
                    refreshFailover();
                }
            } else if (data == 'ELECTING') {
                statusname.innerHTML = 'Electing';
                if(
                  domClass.contains(statusitem, "failover_ok") ||
                  domClass.contains(statusitem, "failover_importing") ||
                  domClass.contains(statusitem, "failover_passive") ||
                  domClass.contains(statusitem, "failover_error")
                  ) {
                    domClass.remove(statusitem, ["failover_ok", "failover_importing", "failover_passive", "failover_error"]);
                    domClass.add(statusitem, "failover_electing");
                    refreshFailover();
                }
            } else if (data == 'IMPORTING') {
                statusname.innerHTML = 'Importing';
                if(
                  domClass.contains(statusitem, "failover_ok") ||
                  domClass.contains(statusitem, "failover_electing") ||
                  domClass.contains(statusitem, "failover_passive") ||
                  domClass.contains(statusitem, "failover_error")
                  ) {
                    domClass.remove(statusitem, ["failover_ok", "failover_electing", "failover_passive", "failover_error"]);
                    domClass.add(statusitem, "failover_importing");
                    refreshFailover();
                }
            } else if (data == 'ERROR') {
                statusname.innerHTML = 'Error';
                if(
                  domClass.contains(statusitem, "failover_ok") ||
                  domClass.contains(statusitem, "failover_electing") ||
                  domClass.contains(statusitem, "failover_importing") ||
                  domClass.contains(statusitem, "failover_passive")
                  ) {
                    domClass.remove(statusitem, ["failover_ok", "failover_electing", "failover_importing", "failover_passive"]);
                    domClass.add(statusitem, "failover_error");
                    refreshFailover();
                }
            } else {
                statusname.innerHTML = 'Standby';
                if(
                  domClass.contains(statusitem, "failover_ok") ||
                  domClass.contains(statusitem, "failover_electing") ||
                  domClass.contains(statusitem, "failover_importing") ||
                  domClass.contains(statusitem, "failover_error")
                  ) {
                    domClass.remove(statusitem, ["failover_ok", "failover_electing", "failover_importing", "failover_error"]);
                    domClass.add(statusitem, "failover_passive");
                    refreshFailover();
                }
            }
            setTimeout(checkFailoverStatus, 7000);
        }, function(data, req, err) {
            setTimeout(checkFailoverStatus, 10000);
        });

    }

    sync_to_peer = function(id) {

        xhr.post('/failover/sync_to_peer/' + id + '/', {
            headers: {"X-CSRFToken": cookie('csrftoken')},
            handleAs: "json"
        }).then(function(data) {
            if(data.error == true) {
                setMessage(gettext('An error occurred while syncing to peer!'), "error");
            }
        });

    }

    failoverForceMaster = function(btn, url) {
      btn.set('disabled', true);
      form = getForm(btn);
      require([
        "dojo/request/xhr"
      ], function(xhr) {
        xhr.post(url, {
          handleAs: 'json',
          headers: {"X-CSRFToken": CSRFToken}
        }).then(function(data) {
          btn.set('disabled', false);
          if(!data.error) {
            setMessage(data.message);
          } else {
            setMessage(data.message, "error");
          }
        });

      });
    }

    failoverPairing = function() {

      pairing = dom.byId("FailoverPairing")
      if(!pairing) {
        return;
      }
      xhr.get(
        '/api/v1.0/failover/failover/?format=json', {
          headers: {"Content-Type": "application/json","X-Requested-From": "WebUI"},
          handleAs: "json"
      }).then(function(data) {
        if(data.length > 0) {
          window.location = '/';
        } else {
          setTimeout(failoverPairing, 5000);
        }
      });


    }

    failoverWaitNode = function() {
      var waiting = dom.byId("failoverWaiting");
      var button = registry.byId("btn_failoverWaitNode");
      if(!button) {
        return;
      }
      var form = getForm(button);
      var dialog = getDialog(button);

      // wait a bit for remote to reboot
      setTimeout(function() {
        xhr.get('/failover/waitnode/', {
          handleAs: 'json'
        }).then(function(data) {
          if(data == 'WAITING') {
            setTimeout(failoverWaitNode, 5000);
          } else if(data == 'UPDATE') {
            waiting.innerHTML = '<p>Standby node successfully rebooted.<br />Failover and proceed to update this node.</p>';
            dialog._size();
            dialog._position();
            domStyle.set(button.domNode, "display", "");
          } else if(data == 'FINISHED') {
            waiting.innerHTML = '<p>Standby node successfully rebooted.<br />Nodes have been updated.</p>';
            dialog._size();
            dialog._position();
            domStyle.set(button.domNode, "display", "");
          }
        });
      }, 90000);
    };

    haStatus = function() {

      en = dom.byId("failover_disabled");
      if(!en) return;

      if(domClass.contains(en, "failover_ha_disabled_A") || domClass.contains(en, "failover_ha_disabled_B")) {
        var dlg = new Dialog({
            title: gettext("HA Status"),
            style: "width: 400px",
            id: "hastatus_dialog",
            href: "/failover/disabled/detail/",
            onHide: function() {
                setTimeout(lang.hitch(this, 'destroyRecursive'), manager.defaultDuration);
            }
        });
        dlg.show();

      }

    }

    checkDisabled = function() {

        var menuitem = dom.byId('failoveren_menuitem');
        var dis = dom.byId('failover_disabled');
        var dis_text = dom.byId('failover_disabled_text');
        if(!dis) return;

        var node = dis.getAttribute("data-node");
        var disabled_class = 'failover_ha_disabled_' + node;
        var enabled_class = 'failover_ha_enabled_' + node;

        var menuDisplay = domStyle.get(menuitem, "display");
        if(menuDisplay == "none") return;

        xhr.get('/failover/disabled/', {
            preventCache: true,
            handleAs: 'json'
        }).then(function(data) {
          if(data.length > 0) {
              domClass.remove(dis, [enabled_class]);
              domClass.add(dis, disabled_class);
              if(data.indexOf('NO_FAILOVER') != -1) {
                dis_text.innerHTML = 'HA Disabled';
              } else {
                dis_text.innerHTML = 'HA Unavailable';
              }
          } else {
              domClass.remove(dis, [disabled_class]);
              domClass.add(dis, enabled_class);
              dis_text.innerHTML = 'HA Enabled';
          }
          setTimeout(checkDisabled, 7000);
        }, function(data) {
          setTimeout(checkDisabled, 7000);
        });
    }

    ready(function() {
      checkDisabled();
    });

});
