import { __decorate, __metadata } from "tslib";
import '@material/web/icon/icon.js';
import '@operato/board/ox-board-creation-card.js';
import gql from 'graphql-tag';
import { css, html, LitElement, nothing } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { keyed } from 'lit/directives/keyed.js';
import { client } from '@operato/graphql';
import { privileged } from '@things-factory/auth-base/dist-client';
let BoardTileList = class BoardTileList extends LitElement {
    constructor() {
        super(...arguments);
        this.boards = [];
        this.favorites = [];
        this.groups = [];
        this.creatable = false;
        this.reorderable = false;
    }
    connectedCallback() {
        super.connectedCallback();
        if (this.reorderable) {
            this.renderRoot.addEventListener('dragstart', (e) => {
                var _a;
                const target = e.target;
                this.draggedItem = target.closest('[card]');
                (_a = e.dataTransfer) === null || _a === void 0 ? void 0 : _a.setData('text/plain', target.innerHTML);
            });
            this.renderRoot.addEventListener('dragover', (e) => {
                e.preventDefault();
                const target = e.target;
                const targetItem = target.closest('[card]');
                if (targetItem && targetItem !== this.draggedItem) {
                    const targetRect = targetItem.getBoundingClientRect();
                    const mousePos = e.clientX - targetRect.left;
                    if (mousePos < targetRect.width / 2) {
                        // 마우스 위치가 아이템 좌측 반절에 있을 때
                        this.renderRoot.insertBefore(this.draggedItem, targetItem);
                    }
                    else {
                        // 마우스 위치가 아이템 우측 반절에 있을 때
                        this.renderRoot.insertBefore(this.draggedItem, targetItem.nextSibling);
                    }
                }
            });
            this.renderRoot.addEventListener('drop', (e) => {
                e.preventDefault();
                const boardIds = Array.from(this.renderRoot.querySelectorAll('[card]'))
                    .map(board => board.getAttribute('id'))
                    .filter(Boolean);
                this.dispatchEvent(new CustomEvent('reordered', {
                    detail: {
                        groupId: this.group,
                        boardIds
                    }
                }));
            });
        }
    }
    render() {
        var boards = this.boards || [];
        return html `
      ${this.creatable
            ? privileged({ privilege: 'mutation', category: 'board' }, html `
              <ox-board-creation-card
                .groups=${this.groups}
                .defaultGroup=${this.group}
                @create-board=${e => this.onCreateBoard(e)}
                card
                create
              ></ox-board-creation-card>
            `)
            : nothing}
      ${keyed(Date.now(), boards.map(board => html `
            <div card draggable="true" id=${board.id}>
              <a href="board-viewer/${board.id}"> <img src=${board.thumbnail} /> </a>

              <div name>${board.name}</div>
              <!-- <div description>${board.description}</div> -->

              <md-icon
                iconBtn
                info
                @click=${e => {
            this.infoBoard(board);
            e.preventDefault();
        }}
                >info</md-icon
              >

              ${(this.favorites || []).includes(board.id)
            ? html ` <md-icon iconBtn favored @click=${e => this.removeFavorite(board.id)}>star</md-icon> `
            : html ` <md-icon iconBtn @click=${e => this.addFavorite(board.id)}>star_border</md-icon> `}
            </div>
          `))}
    `;
    }
    updated(changes) {
        var creationCard = this.renderRoot.querySelector('ox-board-creation-card');
        if (creationCard) {
            creationCard.reset();
        }
    }
    onCreateBoard(e) {
        this.dispatchEvent(new CustomEvent('create-board', {
            detail: e.detail
        }));
    }
    infoBoard(board) {
        this.dispatchEvent(new CustomEvent('info-board', {
            detail: board
        }));
    }
    async removeFavorite(boardId) {
        await client.query({
            query: gql `
        mutation {
          deleteFavorite(routing: "${boardId}")
        }
      `
        });
        this.refreshFavorites();
    }
    async addFavorite(boardId) {
        await client.query({
            query: gql `
        mutation {
          createFavorite(favorite: {
            routing: "${boardId}"
          }) {
            id
            routing
          }
        }
      `
        });
        this.refreshFavorites();
    }
    async refreshFavorites() {
        this.dispatchEvent(new CustomEvent('refresh-favorites'));
    }
};
BoardTileList.styles = [
    css `
      :host {
        overflow: auto;
        padding: var(--popup-content-padding);
        display: grid;
        background-color: var(--md-sys-color-background);

        grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
        grid-auto-rows: var(--card-list-rows-height);
        grid-gap: 20px;
      }

      [card] {
        position: relative;
        align-items: center;
        overflow: hidden;
      }

      [card][create] {
        overflow: visible;
        background-color: initial;
      }

      [card] > a {
        display: flex;
        clip-path: border-box;
      }

      [card]:hover {
        cursor: pointer;
      }

      [name] {
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        margin-top: var(--spacing-small);
        width: calc(100% - 45px);
        color: var(--md-sys-color-on-background);
        font-weight: bolder;
        font-size: var(--fontsize-small);
      }

      img {
        flex: 1;
        object-fit: contain;
      }

      md-icon[iconBtn] {
        float: right;
        margin-top: -20px;
        margin-left: 2px;
        color: var(--board-list-star-color);
        font-size: 1.4em;
      }
      md-icon[info] {
        color: var(--md-sys-color-primary);
      }

      md-icon[iconBtn][favored],
      md-icon[info]:hover {
        color: var(--board-list-star-active-color);
      }

      a {
        display: block;
        border-radius: var(--card-list-border-radius);
        border: var(--border-dim-color);
        box-sizing: border-box;
        color: var(--card-list-color);
        background-color: var(--card-list-background-color);
        margin: 0px;
        height: calc(100% - 25px);
      }

      :host > *:hover [info] {
        opacity: 1;
        -webkit-transition: opacity 0.8s;
        -moz-transition: opacity 0.8s;
        -o-transition: opacity 0.8s;
        transition: opacity 0.8s;
      }

      [draggable='true'] {
        cursor: grab;
      }

      @media screen and (max-width: 800px), screen and (max-height: 600px) {
        ox-board-creation-card {
          display: none;
        }
      }
    `
];
__decorate([
    property({ type: Array }),
    __metadata("design:type", Array)
], BoardTileList.prototype, "boards", void 0);
__decorate([
    property({ type: Array }),
    __metadata("design:type", Array)
], BoardTileList.prototype, "favorites", void 0);
__decorate([
    property({ type: Array }),
    __metadata("design:type", Array)
], BoardTileList.prototype, "groups", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], BoardTileList.prototype, "group", void 0);
__decorate([
    property({ type: Boolean }),
    __metadata("design:type", Boolean)
], BoardTileList.prototype, "creatable", void 0);
__decorate([
    property({ type: String, attribute: 'search-text' }),
    __metadata("design:type", String)
], BoardTileList.prototype, "searchText", void 0);
__decorate([
    property({ type: Boolean, attribute: 'reorderable' }),
    __metadata("design:type", Boolean)
], BoardTileList.prototype, "reorderable", void 0);
BoardTileList = __decorate([
    customElement('board-tile-list')
], BoardTileList);
export { BoardTileList };
//# sourceMappingURL=board-tile-list.js.map