<!--
 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/>.
-->
<confirm-delete-image>
  <material-popup opened="{ props.opened }" onClick="{ props.onClick }">
    <div class="material-popup-title">These images will be deleted</div>
    <div class="material-popup-content">
      <ul>
        <li each="{ image in displayImagesToDelete(props.toDelete, props.tags) }">{ image.name }:{ image.tag }</li>
      </ul>
    </div>
    <div class="material-popup-action">
      <material-button
        class="dialog-button"
        waves-color="var(--hover-background)"
        onClick="{ deleteImages }"
        color="inherit"
        text-color="var(--primary-text)"
      >
        Delete
      </material-button>
      <material-button
        class="dialog-button"
        waves-color="var(--hover-background)"
        onClick="{ props.onClick }"
        color="inherit"
        text-color="var(--primary-text)"
      >
        Cancel
      </material-button>
    </div>
  </material-popup>
  <script>
    import { Http } from '../../scripts/http';
    import router from '../../scripts/router';
    export default {
      displayImagesToDelete(toDelete, tags) {
        const contentDigests = new Set();
        toDelete.forEach((image) => {
          if (image.contentDigest) {
            contentDigests.add(image.contentDigest);
          }
        });
        return tags.filter((image) => contentDigests.has(image.contentDigest));
      },
      deleteImages() {
        this.props.toDelete.forEach((image) => this.getContentDigestThenDelete(image, this.props));
      },
      getContentDigestThenDelete({ name, tag }, opts) {
        const { registryUrl, onNotify, onAuthentication } = opts;
        const oReq = new Http({ onAuthentication });
        const self = this;
        oReq.addEventListener('loadend', function () {
          if (this.status === 200 || this.status === 202) {
            oReq.getContentDigest(function (contentDigest) {
              if (!contentDigest) {
                onNotify(ERROR_CAN_NOT_READ_CONTENT_DIGEST);
              } else {
                self.deleteImage({ name, tag, contentDigest }, opts);
              }
            });
          } else if (this.status === 404) {
            onNotify(`Manifest for ${name}:${tag} not found`, true);
          } else {
            onNotify(this.responseText);
          }
        });
        oReq.open('GET', `${registryUrl}/v2/${name}/manifests/${tag}`);
        oReq.setRequestHeader(
          'Accept',
          'application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.index.v1+json'
        );
        oReq.send();
      },
      deleteImage({ name, tag, contentDigest }, opts) {
        const { registryUrl, ignoreError, onNotify, onAuthentication, onClick } = opts;
        const oReq = new Http({ onAuthentication });
        oReq.addEventListener('loadend', function () {
          if (this.status === 200 || this.status === 202) {
            router.taglist(name);
            onNotify(`Deleting ${name}:${tag} image. Run \`registry garbage-collect config.yml\` on your registry`);
          } else if (this.status === 404) {
            ignoreError ||
              onNotify({
                message: 'Digest not found for this image in your registry.',
                isError: true,
              });
          } else {
            onNotify(this.responseText);
          }
          onClick();
        });
        oReq.open('DELETE', `${registryUrl}/v2/${name}/manifests/${contentDigest}`);
        oReq.setRequestHeader(
          'Accept',
          'application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.manifest.v1+json'
        );
        oReq.addEventListener('error', function () {
          const credMsg = this.withCredentials
            ? ' When you use credentials on a different hostname, the registry server may fail preflight requests. Check FAQ and issue #104.'
            : '';
          onNotify({
            message:
              "An error occurred when deleting image. Check if your server accept DELETE methods Access-Control-Allow-Methods: ['DELETE']." +
              credMsg,
            isError: true,
          });
        });
        oReq.send();
      },
    };
  </script>
  <style>
    :host {
      color: #000;
      list-style-type: disc;
      margin-block-start: 0.7em;
    }

    :host material-popup .content .material-popup-content {
      overflow-y: auto;
      max-height: 250px;
    }
  </style>
</confirm-delete-image>
