$(function () {
  'use strict';

  var apiHostname = window.location.hostname.replace(/^www\./, '');
  var hostname = window.location.hostname.replace(/^www\./, '');
  var baseUrl;

  $.http = $.ajax;
  if (/[a-z]+/.test(apiHostname)) {
    apiHostname = 'api.' + apiHostname;
  }
  else {
    apiHostname = '';
  }
  baseUrl = window.location.protocol.replace(/:$/, '')
    + '://' + apiHostname
    + window.location.host.replace(/^www\./, '').replace(/.[^:]+(:(\d+))?/, '$2')
  ;

  function readConfig() {
    $('input.js-domain').val(hostname);

    return $.http({
      method: 'GET'
    , url: baseUrl + '/api/walnut@daplie.com/init'
    , headers: {
        "Accept" : "application/json; charset=utf-8"
      }
    }).then(function (results) {
      results.le = results.le || {};
      $('input.js-agree-tos').prop('checked', results.le.agreeTos);
      $('input.js-email').val(results.le.email || results.email);
      $('.js-devicename').text(results.hostname);
      $('.js-inets').text(
        results.inets.map(function (a) {
          return 'IPv' + a.family + ' ' + a.address;
        }).join('\n')
        + '\n\n'
        + '# set this device to your account\n'
        + "daplie devices:set -d '" + results.hostname + "'"
          + " -a '" + results.inets.map(function (a) { return a.address; }).join() + "'\n"
        + '\n'
        + '# attach this device to the necessary subdomains\n'
        + "daplie devices:attach -d '" + results.hostname + "'"
          + " -n '" + ($('input.js-domain').val() || '<<domainname>>') + "'\n"
        + "daplie devices:attach -d '" + results.hostname + "'"
          + " -n 'www." + ($('input.js-domain').val() || '<<domainname>>') + "'\n"
        + "daplie devices:attach -d '" + results.hostname + "'"
          + " -n 'api." + ($('input.js-domain').val() || '<<domainname>>') + "'\n"
        + "daplie devices:attach -d '" + results.hostname + "'"
          + " -n 'assets." + ($('input.js-domain').val() || '<<domainname>>') + "'\n"
        + "daplie devices:attach -d '" + results.hostname + "'"
          + " -n 'cloud." + ($('input.js-domain').val() || '<<domainname>>') + "'\n"
        + "daplie devices:attach -d '" + results.hostname + "'"
          + " -n 'api.cloud." + ($('input.js-domain').val() || '<<domainname>>') + "'"
      );
    });
  }

  readConfig();

  $('body').on('submit', 'form.js-form-le', function (ev) {
    ev.preventDefault();

    var data = {
      domain: $('input.js-domain').val()
    , email: $('input.js-email').val()
    , agreeTos: $('input.js-agree-tos').prop('checked')
    };

    if (!data.domain) {
      window.alert("Please enter the primary domain of this device.");
      return;
    }
    if (!data.email) {
      window.alert("Please enter the email of the owner of this device.");
      return;
    }
    if (!data.agreeTos) {
      window.alert("Please click to agree to the Let's Encrypt Subscriber Agreement. This server cannot function without encryption. Currently you must use Let's Encrypt. In the future we will enable other options.");
      return;
    }

    $.http({
      method: 'POST'
    , url: baseUrl + '/api/walnut@daplie.com/init'
    , headers: {
        "Accept" : "application/json; charset=utf-8"
      , "Content-Type": "application/json; charset=utf-8"
      }
    , data: JSON.stringify(data)
    }).then(function (data) {
      var d;
      if (data.error) {
        d = $.Deferred();
        d.reject(new Error(data.error.message));
        return d.promise();
      }
      return data;
    }).then(function (data) {
      console.log('Result:');
      console.log(data);
      if (window.confirm('Hoo hoo! That tickles! Reload page now?')) {
        window.location.reload();
      }
    }, function (err) {
      console.error('Error POSTing form:');
      console.error(err);
      window.alert("Check the console! There's a big, fat error!");
    });
  });
});
