<%
local dsp = require "luci.dispatcher"
-%>

<script type="text/javascript">//<![CDATA[
  var msgInfo;

  var tokenStr = '<%=token%>';
  var clickToDownloadText = '<%:Click to download%>';
  var inProgressText = '<%:Downloading...%>';
  var downloadInProgressNotice = '<%:Download, are you sure to close?%>';
  var downloadSuccessText = '<%:Download successful%>';
  var unexpectedErrorText = '<%:Unexpected error%>';

  function addPageNotice() {
    window.onbeforeunload = function(e) {
      e.returnValue = downloadInProgressNotice;
      return downloadInProgressNotice;
    };
  }

  function removePageNotice() {
    window.onbeforeunload = undefined;
  }

  function onUpdateSuccess(btn) {
    alert(downloadSuccessText);

    if (btn) {
      btn.value = downloadSuccessText;
      btn.placeholder = downloadSuccessText;
      btn.disabled = true;
    }

    window.setTimeout(function () {
      window.location.reload();
    }, 1000);
  }

  function onRequestError(btn, errorMessage) {
    btn.disabled = false;
    btn.value = btn.placeholder;

    if (errorMessage) {
      alert(errorMessage);
    }
  }

  function doAjaxGet(url, data, onResult) {
    new XHR().get(url, data, function(_, json) {
      var resultJson = json || {
        'code': 1,
        'error': unexpectedErrorText
      };

      if (typeof onResult === 'function') {
        onResult(resultJson);
      }
    })
  }

  function downloadClick(btn) {
      if (msgInfo === undefined) {
        checkUpdate(btn);
      } else {
        doDownload(btn);
      }
  }

  function checkUpdate(btn) {
    btn.disabled = true;
    btn.value = inProgressText;

    addPageNotice();

    var ckeckDetailElm = document.getElementById(btn.id + '-detail');

    doAjaxGet('<%=dsp.build_url("admin/nas/filebrowser/check")%>/', {
      token: tokenStr
    }, function (json) {
      removePageNotice();
      if (json.code) {
        eval('Info = undefined');
        onRequestError(btn, json.error);
      } else {
          eval('Info = json');
          btn.disabled = false;
          btn.value = clickToDownloadText;
          btn.placeholder = clickToDownloadText;
      }

      if (ckeckDetailElm) {
        var urlNode = '';
        if (json.version) {
          urlNode = '<em style="color:red;"><%:The latest version:%>' + json.version + '</em>';
          if (json.url && json.url.html) {
            urlNode = '<a href="' + json.url.html + '" target="_blank">' + urlNode + '</a>';
          }
        }
        ckeckDetailElm.innerHTML = urlNode;
      }
	  msgInfo = json;
    });
  }

  function doDownload(btn) {
    btn.disabled = true;
    btn.value = '<%:Downloading...%>';

    addPageNotice();

    var UpdateUrl = '<%=dsp.build_url("admin/nas/filebrowser/download")%>';
    // Download file
    doAjaxGet(UpdateUrl, {
      token: tokenStr,
      url: msgInfo ? msgInfo.url.download : ''
    }, function (json) {
      if (json.code) {
        removePageNotice();
        onRequestError(btn, json.error);
      } else {
        btn.value = '<%:Unpacking...%>';

        // Extract file
        doAjaxGet(UpdateUrl, {
          token: tokenStr,
          task: 'extract',
          file: json.file
        }, function (json) {
          if (json.code) {
            removePageNotice();
            onRequestError(btn, json.error);
          } else {
            btn.value = '<%:Moving...%>';

            // Move file to target dir
            doAjaxGet(UpdateUrl, {
              token: tokenStr,
              task: 'move',
              file: json.file
            }, function (json) {
              removePageNotice();
              if (json.code) {
                onRequestError(btn, json.error);
              } else {
                onUpdateSuccess(btn);
              }
            })
          }
        })
      }
    })
  }
//]]></script>

<%+cbi/valueheader%>
	<% if self:cfgvalue(section) ~= false then %>
		<input class="cbi-button cbi-input-<%=self.inputstyle or "button" %>" type="button"<%=
			attr("name", cbid) ..
			attr("id", self.id or cbid) ..
			attr("value", self.inputtitle or self.title) ..
			ifattr(self.btnclick, "onclick", self.btnclick) ..
			ifattr(self.placeholder, "placeholder")
		%> />
		<span id="<%=self.id or cbid%>-detail"></span>
	<% else %>
		-
	<% end %>
<%+cbi/valuefooter%>