define([
  "exports",
  "./../modules/viewmanager/basesettingsview.js",
  "./../modules/loading/loading.js",
  "./../modules/common/globalize.js",
  "./../modules/emby-elements/emby-input/emby-input.js",
  "./../modules/emby-elements/emby-button/emby-button.js",
  "./../modules/emby-elements/emby-checkbox/emby-checkbox.js",
  "./../modules/emby-elements/emby-select/emby-select.js",
  "./../modules/emby-elements/emby-scroller/emby-scroller.js",
  "./../modules/layoutmanager.js",
  "./../modules/common/usersettings/usersettings.js",
  "./../modules/common/usersettings/usersettingsbuilder.js",
  "./../modules/emby-apiclient/connectionmanager.js",
  "./../modules/listview/listview.js",
], function (
  _exports,
  _basesettingsview,
  _loading,
  _globalize,
  _embyInput,
  _embyButton,
  _embyCheckbox,
  _embySelect,
  _embyScroller,
  _layoutmanager,
  _usersettings,
  _usersettingsbuilder,
  _connectionmanager,
  _listview,
) {
  function getLandingScreenOptionsHtml(type) {
    return (function (type) {
      var list = [];
      return (
        "movies" === type
          ? (list.push({
              name: _globalize.default.translate("Movies"),
              value: "movies",
              isDefault: !0,
            }),
            list.push({
              name: _globalize.default.translate("Suggestions"),
              value: "suggestions",
            }),
            list.push({
              name: _globalize.default.translate("Favorites"),
              value: "favorites",
            }),
            list.push({
              name: _globalize.default.translate("Genres"),
              value: "genres",
            }),
            list.push({
              name: _globalize.default.translate("Collections"),
              value: "collections",
            }),
            list.push({
              name: _globalize.default.translate("Folders"),
              value: "folders",
            }))
          : "musicvideos" === type
          ? (list.push({
              name: _globalize.default.translate("Videos"),
              value: "videos",
              isDefault: !0,
            }),
            list.push({
              name: _globalize.default.translate("Folders"),
              value: "folders",
            }))
          : "tvshows" === type
          ? (list.push({
              name: _globalize.default.translate("Shows"),
              value: "shows",
              isDefault: !0,
            }),
            list.push({
              name: _globalize.default.translate("Suggestions"),
              value: "suggestions",
            }),
            list.push({
              name: _globalize.default.translate("Favorites"),
              value: "favorites",
            }),
            list.push({
              name: _globalize.default.translate("Collections"),
              value: "collections",
            }),
            list.push({
              name: _globalize.default.translate("Genres"),
              value: "genres",
            }),
            list.push({
              name: _globalize.default.translate("Networks"),
              value: "studios",
            }),
            list.push({
              name: _globalize.default.translate("Folders"),
              value: "folders",
            }))
          : "music" === type
          ? (list.push({
              name: _globalize.default.translate("Suggestions"),
              value: "suggestions",
              isDefault: !0,
            }),
            list.push({
              name: _globalize.default.translate("Albums"),
              value: "albums",
            }),
            list.push({
              name: _globalize.default.translate("HeaderAlbumArtists"),
              value: "albumartists",
            }),
            list.push({
              name: _globalize.default.translate("Artists"),
              value: "artists",
            }),
            list.push({
              name: _globalize.default.translate("Playlists"),
              value: "playlists",
            }),
            list.push({
              name: _globalize.default.translate("Genres"),
              value: "genres",
            }),
            list.push({
              name: _globalize.default.translate("Songs"),
              value: "songs",
            }),
            list.push({
              name: _globalize.default.translate("Folders"),
              value: "folders",
            }))
          : "audiobooks" === type
          ? (list.push({
              name: _globalize.default.translate("Suggestions"),
              value: "suggestions",
              isDefault: !0,
            }),
            list.push({
              name: _globalize.default.translate("Books"),
              value: "albums",
            }),
            list.push({
              name: _globalize.default.translate("Authors"),
              value: "artists",
            }),
            list.push({
              name: _globalize.default.translate("Playlists"),
              value: "playlists",
            }),
            list.push({
              name: _globalize.default.translate("Genres"),
              value: "genres",
            }),
            list.push({
              name: _globalize.default.translate("Folders"),
              value: "folders",
            }))
          : "livetv" === type
          ? (list.push({
              name: _globalize.default.translate("Suggestions"),
              value: "suggestions",
              isDefault: !0,
            }),
            list.push({
              name: _globalize.default.translate("Guide"),
              value: "guide",
            }),
            list.push({
              name: _globalize.default.translate("Channels"),
              value: "channels",
            }))
          : "homevideos" === type &&
            (list.push({
              name: _globalize.default.translate("Videos"),
              value: "videos",
            }),
            list.push({
              name: _globalize.default.translate("Photos"),
              value: "photos",
            }),
            list.push({
              name: _globalize.default.translate("Folders"),
              value: "folders",
            })),
        list
      );
    })(type)
      .map(function (o) {
        return (
          '<option value="' +
          (o.isDefault ? "" : o.value) +
          '">' +
          o.name +
          "</option>"
        );
      })
      .join("");
  }
  function renderPerLibrarySettings(context, user, userViews) {
    for (
      var context = context.querySelector(".perLibrarySettings"),
        html = "",
        i = 0,
        length = userViews.length;
      i < length;
      i++
    )
      html += (function (item, user) {
        var html = "",
          folderId = item.Guid || item.Id;
        return (
          ("Channel" !== item.Type &&
            "boxsets" !== item.CollectionType &&
            "playlists" !== item.CollectionType) ||
            (html =
              (html =
                (html += "<div>") +
                '<label><input type="checkbox" is="emby-checkbox" class="chkIncludeInMyMedia" data-folderid="' +
                folderId +
                '"' +
                (-1 ===
                (user.Configuration.MyMediaExcludes || []).indexOf(folderId)
                  ? ' checked="checked"'
                  : "") +
                "/>") +
              "<span>" +
              _globalize.default.translate("DisplayInMyMedia") +
              "</span></label></div>"),
          (html =
            (html =
              -1 ===
              ["playlists", "livetv", "boxsets", "channels"].indexOf(
                item.CollectionType || "",
              )
                ? (html =
                    html +
                    '<label class="fldIncludeInLatest"><input type="checkbox" is="emby-checkbox" class="chkIncludeInLatest" data-folderid="' +
                    folderId +
                    '"' +
                    (-1 ===
                    user.Configuration.LatestItemsExcludes.indexOf(folderId)
                      ? ' checked="checked"'
                      : "") +
                    "/>") +
                  "<span>" +
                  _globalize.default.translate(
                    "DisplayInOtherHomeScreenSections",
                  ) +
                  "</span></label>"
                : html) &&
            '<div class="checkboxListContainer">' + html + "</div>"),
          ("movies" !== item.CollectionType &&
            "tvshows" !== item.CollectionType &&
            "musicvideos" !== item.CollectionType &&
            "music" !== item.CollectionType &&
            "audiobooks" !== item.CollectionType &&
            "livetv" !== item.CollectionType &&
            "homevideos" !== item.CollectionType) ||
            ((folderId =
              "landing-" +
              (user =
                "livetv" === item.CollectionType
                  ? item.CollectionType
                  : folderId)),
            (html =
              (html =
                (html += '<div class="selectContainer">') +
                '<select is="emby-select" class="selectLanding autoSetting autoSave" data-folderid="' +
                user +
                '" label="' +
                _globalize.default.translate("LabelDefaultScreen") +
                '" data-usersettingsfield="' +
                folderId +
                '" data-settingowner="usersettings">') +
              getLandingScreenOptionsHtml(item.CollectionType) +
              "</select></div>")),
          html &&
            ((html =
              "" +
              '<div class="verticalSection">' +
              '<h2 class="sectionTitle">' +
              item.Name +
              "</h2>" +
              html),
            (html += "</div>")),
          html
        );
      })(userViews[i], user);
    context.innerHTML = html;
  }
  function loadForm(context, user, userSettings, apiClient) {
    apiClient = apiClient.getUserViews({ IncludeHidden: !0 }, user.Id);
    return Promise.all([apiClient]).then(function (responses) {
      !(function (context, result) {
        var html = "";
        (html += result.Items.map(function (view) {
          var currentHtml = "";
          return (
            (currentHtml +=
              '<div class="listItem listItem-border viewItem" data-viewid="' +
              (view.Guid || view.Id) +
              '">') +
            '<i class="md-icon listItemIcon">&#xE2C8;</i>' +
            '<div class="listItemBody">' +
            "<div>" +
            view.Name +
            "</div>" +
            "</div>" +
            ('<button type="button" is="paper-icon-button-light" class="btnViewItemUp btnViewItemMove" title="' +
              _globalize.default.translate("Up") +
              '" aria-label="' +
              _globalize.default.translate("Up") +
              '"><i class="md-icon">&#xE316;</i></button>') +
            ('<button type="button" is="paper-icon-button-light" class="btnViewItemDown btnViewItemMove" title="' +
              _globalize.default.translate("Down") +
              '" aria-label="' +
              _globalize.default.translate("Down") +
              '"><i class="md-icon">&#xE313;</i></button>') +
            "</div>"
          );
        }).join("")),
          (context.querySelector(".viewOrderList").innerHTML = html);
      })(context, responses[0]),
        renderPerLibrarySettings(context, user, responses[0].Items),
        _loading.default.hide();
    });
  }
  function getCheckboxItems(selector, context, isChecked) {
    for (
      var inputs = context.querySelectorAll(selector),
        list = [],
        i = 0,
        length = inputs.length;
      i < length;
      i++
    )
      inputs[i].checked === isChecked && list.push(inputs[i]);
    return list;
  }
  function onSubmit(e) {
    return e && e.preventDefault(), !1;
  }
  function onTVHomeScreenChange() {
    var fldHomeFocusPreviews = this.closest("form").querySelector(
      ".fldHomeFocusPreviews",
    );
    _layoutmanager.default.tv && "vertical" === this.value
      ? fldHomeFocusPreviews.classList.remove("hide")
      : fldHomeFocusPreviews.classList.add("hide");
  }
  function embed(options, self) {
    options.element.querySelector(".viewOrderList").addEventListener(
      "click",
      function (e) {
        if ((target = e.target.closest(".btnViewItemMove"))) {
          var viewItem = target.closest(".viewItem");
          if (
            (viewItem &&
              (target.classList.contains("btnViewItemDown")
                ? (target = viewItem.nextElementSibling) &&
                  (viewItem.parentNode.removeChild(viewItem),
                  target.parentNode.insertBefore(
                    viewItem,
                    target.nextElementSibling,
                  ),
                  (changed = !0))
                : (target = viewItem.previousElementSibling) &&
                  (viewItem.parentNode.removeChild(viewItem),
                  target.parentNode.insertBefore(viewItem, target),
                  (changed = !0))),
            changed)
          ) {
            for (
              var viewItem = this.options,
                target = _connectionmanager.default.getApiClient(
                  viewItem.serverId,
                ),
                changed = viewItem.userId,
                viewItem = {},
                viewItems = e.target
                  .closest("form")
                  .querySelectorAll(".viewItem"),
                orderedViews = [],
                i = 0,
                length = viewItems.length;
              i < length;
              i++
            )
              orderedViews.push(viewItems[i].getAttribute("data-viewid"));
            (viewItem.OrderedViews = orderedViews),
              target.updatePartialUserConfiguration(changed, viewItem);
          }
        }
      }.bind(self),
    ),
      options.element
        .querySelector("form")
        .addEventListener("submit", onSubmit.bind(self)),
      options.element.addEventListener(
        "change",
        function (e) {
          var fldIncludeInLatest,
            options = this.options,
            apiClient = _connectionmanager.default.getApiClient(
              options.serverId,
            ),
            options = options.userId,
            context = e.target.closest("form"),
            chkIncludeInMyMedia = e.target.closest(".chkIncludeInMyMedia");
          chkIncludeInMyMedia
            ? ((fldIncludeInLatest = chkIncludeInMyMedia
                .closest(".verticalSection")
                .querySelector(".fldIncludeInLatest")) &&
                (chkIncludeInMyMedia.checked
                  ? fldIncludeInLatest.classList.remove("hide")
                  : fldIncludeInLatest.classList.add("hide")),
              ((chkIncludeInMyMedia = {}).MyMediaExcludes = getCheckboxItems(
                ".chkIncludeInMyMedia",
                context,
                !1,
              ).map(function (i) {
                return i.getAttribute("data-folderid");
              })),
              apiClient.updatePartialUserConfiguration(
                options,
                chkIncludeInMyMedia,
              ))
            : e.target.closest(".chkIncludeInLatest") &&
              (((fldIncludeInLatest = {}).LatestItemsExcludes =
                getCheckboxItems(".chkIncludeInLatest", context, !1).map(
                  function (i) {
                    return i.getAttribute("data-folderid");
                  },
                )),
              apiClient.updatePartialUserConfiguration(
                options,
                fldIncludeInLatest,
              ));
        }.bind(self),
      );
    self = options.element.querySelector(".selectTVHomeScreenContainer");
    _layoutmanager.default.tv
      ? self.classList.remove("hide")
      : self.classList.add("hide"),
      options.element
        .querySelector(".selectTVHomeScreen")
        .addEventListener("change", onTVHomeScreenChange);
  }
  function HomeScreenSettings(options) {
    embed((this.options = options), this);
  }
  function View(view, params) {
    _basesettingsview.default.apply(this, arguments);
    var apiClient = _connectionmanager.default.getApiClient(params.serverId),
      userId = params.userId || apiClient.getCurrentUserId(),
      userSettings =
        userId === apiClient.getCurrentUserId()
          ? _usersettings.default
          : new _usersettingsbuilder.default(),
      apiClient = {
        serverId: apiClient.serverId(),
        userId: userId,
        element: view.querySelector(".settingsContainer"),
        userSettings: userSettings,
      };
    (this.settingsOptions = apiClient),
      (this.settingsInstance = new HomeScreenSettings(this.settingsOptions));
  }
  Object.defineProperty(_exports, "__esModule", { value: !0 }),
    (_exports.default = void 0),
    (HomeScreenSettings.prototype.loadData = function () {
      var self = this,
        context = self.options.element,
        userId = (_loading.default.show(), self.options.userId),
        apiClient = _connectionmanager.default.getApiClient(
          self.options.serverId,
        ),
        userSettings = self.options.userSettings;
      return (
        (function (context) {
          for (
            var elems = context.querySelectorAll('option[value="nextup"]'),
              i = 0,
              length = elems.length;
            i < length;
            i++
          )
            elems[i].innerHTML =
              _globalize.default.translate("HeaderNextUp") + " (Legacy)";
        })(context),
        apiClient.getUser(userId).then(function (user) {
          return (
            (self.options.user = user),
            (userId === apiClient.getCurrentUserId()
              ? Promise.resolve()
              : userSettings.setUserInfo(userId, apiClient)
            ).then(function () {
              return loadForm(context, user, 0, apiClient);
            })
          );
        })
      );
    }),
    (HomeScreenSettings.prototype.submit = function () {
      onSubmit.call(this);
    }),
    (HomeScreenSettings.prototype.destroy = function () {
      this.options = null;
    }),
    Object.assign(View.prototype, _basesettingsview.default.prototype),
    (View.prototype.loadSettingsInternal = function () {
      var instance = this;
      return this.settingsInstance.loadData().then(function () {
        return instance.loadAutoSettings();
      });
    }),
    (View.prototype.getAutoSettingsObjectsPromises = function () {
      var options,
        list =
          _basesettingsview.default.prototype.getAutoSettingsObjectsPromises.apply(
            this,
            arguments,
          );
      return (
        list.push(
          ((options = this.settingsOptions),
          Promise.resolve({
            key: "userconfiguration",
            value: options.user.Configuration,
          })),
        ),
        list
      );
    }),
    (View.prototype.getUserConfigurationUserId = function () {
      return this.settingsOptions.userId;
    }),
    (View.prototype.getNamedSettingsOwner = function (owner) {
      switch (owner) {
        case "usersettings":
          return this.settingsOptions.userSettings;
        case "userconfiguration":
          return this.settingsOptions.user.Configuration;
        default:
          return _basesettingsview.default.prototype.getNamedSettingsOwner.apply(
            this,
            arguments,
          );
      }
    }),
    (View.prototype.onPause = function () {
      this.settingsInstance && this.settingsInstance.submit(),
        _basesettingsview.default.prototype.onPause.apply(this, arguments);
    }),
    (View.prototype.destroy = function () {
      _basesettingsview.default.prototype.destroy.apply(this, arguments),
        this.settingsInstance &&
          (this.settingsInstance.destroy(), (this.settingsInstance = null)),
        (this.settingsOptions = null);
    }),
    (_exports.default = View);
});
