import { __decorate, __metadata } from "tslib";
import '@operato/attachment/ox-attachment-list.js';
import { css, html } from 'lit';
import { customElement, query } from 'lit/decorators.js';
import gql from 'graphql-tag';
import { i18next, localize } from '@operato/i18n';
import { PageView } from '@operato/shell';
import { OxAttachmentList } from '@operato/attachment/ox-attachment-list.js';
import { client } from '@operato/graphql';
async function fetchDataFromURL(fileURL) {
    try {
        const response = await fetch(fileURL);
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        const blob = await response.blob(); // 파일 데이터를 Blob으로 변환
        if (blob.size === 0) {
            throw new Error('Content is empty'); // Content가 비어 있으면 예외
        }
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (event) => {
                const dataURL = event.target.result;
                resolve(dataURL);
            };
            reader.onerror = (event) => {
                reject(event.error);
            };
            reader.readAsDataURL(blob); // Blob을 Data URL로 읽기
        });
    }
    catch (error) {
        throw error;
    }
}
let AttachmentListPage = class AttachmentListPage extends localize(i18next)(PageView) {
    get context() {
        var _a;
        return {
            title: i18next.t('title.attachment list'),
            search: {
                handler: search => {
                    this.grist.searchText = search;
                },
                value: ((_a = this.grist) === null || _a === void 0 ? void 0 : _a.searchText) || ''
            },
            board_topmenu: true,
            exportable: {
                name: i18next.t('title.attachment list'),
                data: this.exportHandler.bind(this)
            },
            importable: {
                handler: this.importHandler.bind(this)
            }
        };
    }
    render() {
        return html ` <ox-attachment-list .creatable=${true} without-search></ox-attachment-list> `;
    }
    get grist() {
        return this.attachmentList.grist;
    }
    languageUpdated(i18next) {
        this.attachmentList.requestUpdate();
    }
    async pageInitialized() {
        await this.updateComplete;
        this.attachmentList.refreshAttachments();
    }
    async exportHandler() {
        const records = this.grist.data.records;
        const data = {};
        for (const record of records) {
            const { id, name, mimetype, encoding, category, fullpath } = record;
            try {
                const dataURL = await fetchDataFromURL(fullpath);
                id &&
                    (data[id] = {
                        id,
                        name,
                        mimetype,
                        encoding,
                        category,
                        contents: dataURL
                    });
            }
            catch (err) {
                console.log(name, err);
            }
        }
        return data;
    }
    async importHandler(data, file) {
        await client.mutate({
            mutation: gql `
        mutation importAttachments($file: Upload!) {
          importAttachments(file: $file) {
            id
            name
            description
            path
          }
        }
      `,
            variables: {
                file
            },
            context: { hasUpload: true }
        });
        this.grist.fetch();
    }
};
AttachmentListPage.styles = [
    css `
      :host {
        display: flex;
      }
    `
];
__decorate([
    query('ox-attachment-list'),
    __metadata("design:type", OxAttachmentList)
], AttachmentListPage.prototype, "attachmentList", void 0);
AttachmentListPage = __decorate([
    customElement('attachment-list-page')
], AttachmentListPage);
export { AttachmentListPage };
//# sourceMappingURL=attachment-list-page.js.map