import * as i1 from '@angular/common';
import { CommonModule, NgOptimizedImage } from '@angular/common';
import * as i0 from '@angular/core';
import { EventEmitter, Output, ViewChild, ChangeDetectionStrategy, Component } from '@angular/core';
import { SdButton } from '@sd-angular/core/components/button';
import { SdModal } from '@sd-angular/core/components/modal';
import * as uuid from 'uuid';

class SdPreviewImage {
    cd;
    modal;
    close = new EventEmitter();
    title = 'Xem ảnh';
    thumbnailPosition = 'right';
    activeIndex = 0;
    images = [];
    constructor(cd) {
        this.cd = cd;
    }
    #loadImages = async (urlOrFiles) => {
        urlOrFiles = urlOrFiles.filter(url => !!url);
        // Xử lý nếu là url thì thực hiện fetch lấy blob rồi từ blob => file
        const promises = urlOrFiles.map(async (urlOrFile) => {
            if (typeof urlOrFile === 'string') {
                return fetch(urlOrFile)
                    .then(async (r) => {
                    const blob = await r.blob();
                    // Lấy filename dựa vào url src
                    const baseSrc = urlOrFile.split('?')[0];
                    const filename = baseSrc.substring(baseSrc.lastIndexOf('/') + 1);
                    const file = new File([blob], filename);
                    const image = {
                        id: uuid.v4(),
                        blobSrc: URL.createObjectURL(file),
                        src: urlOrFile,
                        name: file.name,
                        size: file.size,
                    };
                    return image;
                })
                    .catch(err => {
                    console.error(err);
                    return null;
                });
            }
            else {
                if (urlOrFile.type.split('/')[0] === 'image') {
                    const image = {
                        id: uuid.v4(),
                        blobSrc: URL.createObjectURL(urlOrFile),
                        name: urlOrFile.name,
                        size: urlOrFile.size,
                    };
                    return image;
                }
                return null;
            }
        });
        this.images = (await Promise.all(promises)).filter(image => image !== null);
    };
    // Nên sử dụng urlOrFiles ở tham số khi open thay vì dùng @Input để component sử dụng sẽ chỉ cần map ở hàm khi gọi open thay vì phải mất công map mọi lúc để binding vào @Input
    open = async (urlOrFiles) => {
        if (!Array.isArray(urlOrFiles)) {
            return;
        }
        await this.#loadImages(urlOrFiles);
        this.#reset();
        this.modal?.open();
        this.cd.markForCheck();
    };
    onClickThumbnailImage = (index) => {
        this.activeIndex = index;
        this.cd.markForCheck();
    };
    updateCurrentImage = (direction) => {
        this.activeIndex = (this.activeIndex + direction + this.images.length) % this.images.length;
        this.#scrollView(this.activeIndex, direction === 1 ? 'start' : 'end');
        this.cd.markForCheck();
    };
    onClose = () => {
        this.close.emit();
    };
    #scrollView = (index, type) => {
        const nameId = 'thumbnailImage' + index;
        const element = document.getElementById(nameId);
        if (!element) {
            return;
        }
        const blockType = type || 'start';
        element.scrollIntoView({ behavior: 'smooth', block: blockType });
    };
    #reset = () => {
        this.activeIndex = 0;
    };
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdPreviewImage, deps: [{ token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.17", type: SdPreviewImage, isStandalone: true, selector: "sd-preview-image", outputs: { close: "close" }, viewQueries: [{ propertyName: "modal", first: true, predicate: SdModal, descendants: true }], ngImport: i0, template: "<sd-modal [title]=\"title\" (sdClosed)=\"close.emit()\" #modal>\r\n  <div class=\"p-16\" style=\"overflow: hidden; height: 100%\">\r\n    <!-- Main image -->\r\n    @if (images.length) {\r\n      <div style=\"gap: 8px;\" class=\"image-gallery\">\r\n        <div class=\"thumbnail-container\">\r\n          @for (image of images; track image.id; let i = $index) {\r\n            <button\r\n              type=\"button\"\r\n              class=\"thumbnail-wrapper\"\r\n              (click)=\"onClickThumbnailImage(i)\"\r\n              [ngStyle]=\"{\r\n                border: activeIndex === i ? '2px solid #2962ff' : 'none'\r\n              }\">\r\n              @if (image.src) {\r\n                <img fill loading=\"lazy\" [ngSrc]=\"image.src\" alt=\"thumbnail\" [id]=\"image.id\" class=\"thumbnail-img\" />\r\n              } @else {\r\n                <img fill loading=\"lazy\" [src]=\"image.blobSrc\" alt=\"thumbnail\" [id]=\"image.id\" class=\"thumbnail-img\" />\r\n              }\r\n            </button>\r\n          }\r\n        </div>\r\n        <div class=\"main-image-container\" #mainImage>\r\n          @let activedImage = images[activeIndex];\r\n          @if (activedImage.src) {\r\n            <img fill priority [ngSrc]=\"activedImage.src\" class=\"main-image\" alt=\"Main display image\" />\r\n          } @else {\r\n            <img fill priority [src]=\"activedImage.blobSrc!\" class=\"main-image\" alt=\"Main display image\" />\r\n          }\r\n          <sd-button prefixIcon=\"arrow_forward_ios\" class=\"next-icon\" (click)=\"updateCurrentImage(1)\"></sd-button>\r\n          <sd-button prefixIcon=\"arrow_back_ios_new\" class=\"back-icon\" (click)=\"updateCurrentImage(-1)\"></sd-button>\r\n        </div>\r\n      </div>\r\n    } @else {\r\n      <div class=\"no-image d-flex justify-content-center align-items-center flex-column m-20\" style=\"height: 80%\">\r\n        <i class=\"icon-no-image mb-16\"></i>\r\n        <div>Kh\u00F4ng c\u00F3 th\u00F4ng tin \u1EA3nh</div>\r\n      </div>\r\n    }\r\n  </div>\r\n</sd-modal>\r\n", styles: [".image-gallery{display:flex;width:100%;max-height:60vh;min-height:60vh}.image-gallery .main-image-container{flex:1;position:relative}.image-gallery .main-image-container .next-icon{position:absolute;top:45%;right:10px;cursor:pointer;color:#000;z-index:9999}.image-gallery .main-image-container .back-icon{position:absolute;top:45%;left:0;cursor:pointer;color:#000;z-index:9999}.image-gallery .thumbnail-container{width:120px;overflow-y:auto;display:flex;flex-direction:column;gap:8px;box-sizing:border-box}.image-gallery .thumbnail-wrapper{position:relative;width:100px;aspect-ratio:1;flex:0 0 auto;overflow:hidden;padding:0;border:none;background:transparent}.image-gallery .thumbnail-wrapper .thumbnail-img{object-fit:cover;width:100%;height:100%;display:block}.image-gallery .main-image{object-fit:contain;width:100%;height:100%;display:block}\n"], dependencies: [{ kind: "component", type: SdModal, selector: "sd-modal", inputs: ["title", "color", "width", "height", "view", "lazyLoadContent"], outputs: ["sdClosed"] }, { kind: "component", type: SdButton, selector: "sd-button", inputs: ["autoId", "type", "color", "size", "fontSet", "title", "width", "tooltip", "prefixIcon", "suffixIcon", "disabled", "loading"], outputs: ["click"] }, { kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i1.NgStyle, selector: "[ngStyle]", inputs: ["ngStyle"] }, { kind: "directive", type: NgOptimizedImage, selector: "img[ngSrc]", inputs: ["ngSrc", "ngSrcset", "sizes", "width", "height", "loading", "priority", "loaderParams", "disableOptimizedSrcset", "fill", "placeholder", "placeholderConfig", "src", "srcset"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdPreviewImage, decorators: [{
            type: Component,
            args: [{ selector: 'sd-preview-image', imports: [SdModal, SdButton, CommonModule, NgOptimizedImage], changeDetection: ChangeDetectionStrategy.OnPush, template: "<sd-modal [title]=\"title\" (sdClosed)=\"close.emit()\" #modal>\r\n  <div class=\"p-16\" style=\"overflow: hidden; height: 100%\">\r\n    <!-- Main image -->\r\n    @if (images.length) {\r\n      <div style=\"gap: 8px;\" class=\"image-gallery\">\r\n        <div class=\"thumbnail-container\">\r\n          @for (image of images; track image.id; let i = $index) {\r\n            <button\r\n              type=\"button\"\r\n              class=\"thumbnail-wrapper\"\r\n              (click)=\"onClickThumbnailImage(i)\"\r\n              [ngStyle]=\"{\r\n                border: activeIndex === i ? '2px solid #2962ff' : 'none'\r\n              }\">\r\n              @if (image.src) {\r\n                <img fill loading=\"lazy\" [ngSrc]=\"image.src\" alt=\"thumbnail\" [id]=\"image.id\" class=\"thumbnail-img\" />\r\n              } @else {\r\n                <img fill loading=\"lazy\" [src]=\"image.blobSrc\" alt=\"thumbnail\" [id]=\"image.id\" class=\"thumbnail-img\" />\r\n              }\r\n            </button>\r\n          }\r\n        </div>\r\n        <div class=\"main-image-container\" #mainImage>\r\n          @let activedImage = images[activeIndex];\r\n          @if (activedImage.src) {\r\n            <img fill priority [ngSrc]=\"activedImage.src\" class=\"main-image\" alt=\"Main display image\" />\r\n          } @else {\r\n            <img fill priority [src]=\"activedImage.blobSrc!\" class=\"main-image\" alt=\"Main display image\" />\r\n          }\r\n          <sd-button prefixIcon=\"arrow_forward_ios\" class=\"next-icon\" (click)=\"updateCurrentImage(1)\"></sd-button>\r\n          <sd-button prefixIcon=\"arrow_back_ios_new\" class=\"back-icon\" (click)=\"updateCurrentImage(-1)\"></sd-button>\r\n        </div>\r\n      </div>\r\n    } @else {\r\n      <div class=\"no-image d-flex justify-content-center align-items-center flex-column m-20\" style=\"height: 80%\">\r\n        <i class=\"icon-no-image mb-16\"></i>\r\n        <div>Kh\u00F4ng c\u00F3 th\u00F4ng tin \u1EA3nh</div>\r\n      </div>\r\n    }\r\n  </div>\r\n</sd-modal>\r\n", styles: [".image-gallery{display:flex;width:100%;max-height:60vh;min-height:60vh}.image-gallery .main-image-container{flex:1;position:relative}.image-gallery .main-image-container .next-icon{position:absolute;top:45%;right:10px;cursor:pointer;color:#000;z-index:9999}.image-gallery .main-image-container .back-icon{position:absolute;top:45%;left:0;cursor:pointer;color:#000;z-index:9999}.image-gallery .thumbnail-container{width:120px;overflow-y:auto;display:flex;flex-direction:column;gap:8px;box-sizing:border-box}.image-gallery .thumbnail-wrapper{position:relative;width:100px;aspect-ratio:1;flex:0 0 auto;overflow:hidden;padding:0;border:none;background:transparent}.image-gallery .thumbnail-wrapper .thumbnail-img{object-fit:cover;width:100%;height:100%;display:block}.image-gallery .main-image{object-fit:contain;width:100%;height:100%;display:block}\n"] }]
        }], ctorParameters: () => [{ type: i0.ChangeDetectorRef }], propDecorators: { modal: [{
                type: ViewChild,
                args: [SdModal]
            }], close: [{
                type: Output
            }] } });

/**
 * Generated bundle index. Do not edit.
 */

export { SdPreviewImage };
//# sourceMappingURL=sd-angular-core-components-preview.mjs.map
