<!--
Copyright (C) 2016-2023 Jones Magloire @Joxit

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
-->
<image-content-digest>
  <div title="{ getTitle(props.image, state.chars) }">{ getContentDigest(props.image, state.chars) }</div>
  <script>
    export default {
      onMounted(props, state) {
        this.load(props, state);
      },
      onUpdated(props, state) {
        this.load(props, state);
      },
      load(props, state) {
        if (props.image.contentDigest) {
          return;
        }
        state.chars = -1;
        props.image.one('content-digest', (contentDigest) => {
          this.contentDigest = contentDigest;
          props.image.on('content-digest-chars', this.onResize);
          props.image.trigger('get-content-digest-chars');
        });
        props.image.trigger('get-content-digest');
      },
      onResize(chars) {
        if (chars !== this.state.chars) {
          this.update({
            chars,
          });
        }
      },
      getTitle(image, chars) {
        return chars >= 70 ? '' : image.contentDigest || '';
      },
      getContentDigest(image, chars) {
        if (chars >= 70) {
          return image.contentDigest || '';
        } else if (chars <= 0) {
          return '';
        } else {
          return image.contentDigest && image.contentDigest.slice(0, chars) + '...';
        }
      },
    };
  </script>
</image-content-digest>
