"use strict";

exports.__esModule = true;
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _reactUse = require("react-use");

var _hooks = require("subfirelib/hooks");

var _LoadingCard = _interopRequireDefault(require("subfirelib/loader/LoadingCard"));

var _styles = require("@material-ui/core/styles");

var _Typography = _interopRequireDefault(require("@material-ui/core/Typography"));

var _Table = _interopRequireDefault(require("@material-ui/core/Table"));

var _TableBody = _interopRequireDefault(require("@material-ui/core/TableBody"));

var _TableCell = _interopRequireDefault(require("@material-ui/core/TableCell"));

var _TableHead = _interopRequireDefault(require("@material-ui/core/TableHead"));

var _TableRow = _interopRequireDefault(require("@material-ui/core/TableRow"));

var _Paper = _interopRequireDefault(require("@material-ui/core/Paper"));

var _Button = _interopRequireDefault(require("@material-ui/core/Button"));

var _IconButton = _interopRequireDefault(require("@material-ui/core/IconButton"));

var _Hidden = _interopRequireDefault(require("@material-ui/core/Hidden"));

var _DeleteForever = _interopRequireDefault(require("@material-ui/icons/DeleteForever"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

/* eslint react/prop-types: 0 */
const useStyles = (0, _styles.makeStyles)(theme => ({
  root: {
    width: '100%',
    marginTop: theme.spacing(3),
    overflowX: 'auto',
    backgroundColor: '#000000'
  },
  table: {
    minWidth: 360
  },
  tableCell: {
    fontSize: 14
  },
  unsetButton: {
    fontWeight: 'inherit',
    fontSize: 18,
    textTransform: 'inherit',
    letterSpacing: 'inherit',
    lineHeight: 'inherit',
    padding: 0
  }
}));

const capitalize = s => {
  if (typeof s !== 'string') return '';
  return s.charAt(0).toUpperCase() + s.slice(1);
};

function BookmarksBrowser(props) {
  const {
    subsonic,
    isLoggedIn,
    getObject
  } = (0, _hooks.useSubsonic)();
  const [loading, setLoading] = (0, _hooks.useLoadingState)();
  const {
    bookmarks,
    deleteBookmark
  } = (0, _hooks.useBookmarks)({
    subsonic,
    isLoggedIn,
    loading,
    setLoading
  });
  const {
    onClick
  } = props;
  const classes = useStyles();
  const [objectMap, {
    set
  }] = (0, _reactUse.useMap)({});
  (0, _react.useEffect)(() => {
    if (bookmarks != null && bookmarks.length) (async function () {
      let data, comment;

      for (const b of bookmarks) {
        try {
          comment = b.comment;
          comment = comment.replace(/&quot;/g, '"'); //ampache hack

          data = JSON.parse(comment);

          if (data.bookmarkSource !== 'SubFire') {
            // console.warn(data);
            set(b.entry.id, {
              contextObject: null,
              contextData: null,
              contextString: 'Not a SubFire Bookmark'
            });
          } else {
            const o = await getObject(data.type, data.id);
            const newData = {
              contextObject: o,
              contextData: data,
              contextString: capitalize(o ? (data.type ? data.type + ' ' : '') + (o.name || o.title || o.album) : data.type ? data.type + ' ' + data.id : '')
            };
            set(b.entry.id, newData);
          }
        } catch (e) {
          // console.error(e);
          console.warn('not a subfire bookmark', JSON.stringify(comment));
          set(b.entry.id, {
            contextObject: null,
            contextData: null,
            contextString: comment.indexOf('DSub') >= 0 ? comment : 'Not a SubFire Bookmark'
          });
        }
      }
    })();
  }, [bookmarks, set]); // eslint-disable-line

  const tableData = (bookmarks || []).map((b, i, a) => {
    const bookmarkDate = new Date(Date.parse(b.created));
    const context = objectMap[b.entry.id];
    const e = Object.assign({}, b.entry, {
      position: b.position
    }, {
      contextData: context == null ? void 0 : context.contextData,
      contextObject: context == null ? void 0 : context.contextObject,
      contextString: context == null ? void 0 : context.contextString,
      bookmarkDate
    });
    return e;
  }, []);

  const handleRowClick = (evt, bookmark) => {
    // console.log('bookmark clicked', bookmark);
    const d = bookmark.contextData;
    let path;

    if (d) {
      // fix the old album since album now goes to directory browser
      if (d.type === 'album') {
        d.type = 'directoryAction';
        d.mode = 'all';
      }

      path = '/bookmark/' + bookmark.id + '/' + bookmark.position + '/loading/' + d.type + '/' + d.id;
      if (d.mode) path += '/' + d.mode;
    } else {
      // non-subfire bookmarks
      path = '/bookmark/' + bookmark.id + '/' + bookmark.position + '/loading/song/' + bookmark.id;
    }

    onClick(bookmark, path);
  };

  const handleDeleteClick = (evt, bookmark) => {
    if (bookmark) {
      deleteBookmark(bookmark);
    }

    evt.stopPropagation();
    return false;
  };

  let warning = null; // if (remotes.remoteState === 'sender') warning = (<Typography>Note: currently, bookmark loading does not work correctly over remote casting.</Typography>);

  let nobookmarks = null;

  if (bookmarks !== null && tableData.length === 0) {
    nobookmarks = /*#__PURE__*/_react.default.createElement(_Typography.default, {
      variant: "h4"
    }, "No Bookmarks have been stored.");
  }

  return /*#__PURE__*/_react.default.createElement(_Paper.default, {
    className: classes.root,
    elevation: 0
  }, loading && /*#__PURE__*/_react.default.createElement(_LoadingCard.default, {
    object: loading,
    top: 0
  }), !loading && warning, /*#__PURE__*/_react.default.createElement(_Table.default, {
    className: classes.table
  }, /*#__PURE__*/_react.default.createElement(_TableHead.default, null, /*#__PURE__*/_react.default.createElement(_TableRow.default, null, /*#__PURE__*/_react.default.createElement(_TableCell.default, {
    className: classes.tableCell,
    size: "small"
  }), /*#__PURE__*/_react.default.createElement(_TableCell.default, {
    className: classes.tableCell,
    size: "small"
  }, "Title"), /*#__PURE__*/_react.default.createElement(_TableCell.default, {
    className: classes.tableCell,
    size: "small"
  }, "Context"), /*#__PURE__*/_react.default.createElement(_Hidden.default, {
    xsDown: true
  }, /*#__PURE__*/_react.default.createElement(_TableCell.default, {
    className: classes.tableCell,
    size: "small"
  }, "Bookmarked")), /*#__PURE__*/_react.default.createElement(_TableCell.default, {
    className: classes.tableCell,
    size: "small"
  }, "Delete"))), /*#__PURE__*/_react.default.createElement(_TableBody.default, null, tableData.map(n => {
    return /*#__PURE__*/_react.default.createElement(_TableRow.default, {
      key: n.id,
      onClick: event => handleRowClick(event, n)
    }, /*#__PURE__*/_react.default.createElement(_TableCell.default, {
      className: classes.tableCell,
      size: "small"
    }, /*#__PURE__*/_react.default.createElement("img", {
      style: {
        width: 40,
        height: 'auto'
      },
      alt: "",
      src: subsonic.getCoverArtURL(n.coverArt, 40)
    })), /*#__PURE__*/_react.default.createElement(_TableCell.default, {
      className: classes.tableCell,
      size: "small"
    }, /*#__PURE__*/_react.default.createElement(_Button.default, {
      className: classes.unsetButton,
      onClick: event => handleRowClick(event, n)
    }, n.title.substring(0, 100))), /*#__PURE__*/_react.default.createElement(_TableCell.default, {
      className: classes.tableCell,
      size: "small"
    }, n.contextString), /*#__PURE__*/_react.default.createElement(_Hidden.default, {
      xsDown: true
    }, /*#__PURE__*/_react.default.createElement(_TableCell.default, {
      className: classes.tableCell,
      size: "small"
    }, n.bookmarkDate.toLocaleString())), /*#__PURE__*/_react.default.createElement(_TableCell.default, {
      className: classes.tableCell,
      size: "small"
    }, /*#__PURE__*/_react.default.createElement(_IconButton.default, {
      onClick: event => handleDeleteClick(event, n)
    }, /*#__PURE__*/_react.default.createElement(_DeleteForever.default, null))));
  }))), !loading && nobookmarks);
}

var _default = BookmarksBrowser;
exports.default = _default;