import * as plugins from '../plugins.js';
import * as shared from './shared/index.js';
import * as appstate from '../appstate.js';
import {
  DeesElement,
  customElement,
  html,
  state,
  css,
  cssManager,
  type TemplateResult,
} from '@design.estate/dees-element';

@customElement('ob-view-tokens')
export class ObViewTokens extends DeesElement {
  @state()
  accessor registriesState: appstate.IRegistriesState = {
    tokens: [],
    registryStatus: null,
  };

  constructor() {
    super();

    const registriesSub = appstate.registriesStatePart
      .select((s) => s)
      .subscribe((newState) => {
        this.registriesState = newState;
      });
    this.rxSubscriptions.push(registriesSub);
  }

  public static styles = [
    cssManager.defaultStyles,
    shared.viewHostCss,
    css``,
  ];

  async connectedCallback() {
    super.connectedCallback();
    await appstate.registriesStatePart.dispatchAction(
      appstate.fetchRegistryTokensAction,
      null,
    );
  }

  public render(): TemplateResult {
    const globalTokens = this.registriesState.tokens.filter((t) => t.type === 'global');
    const ciTokens = this.registriesState.tokens.filter((t) => t.type === 'ci');

    return html`
      <ob-sectionheading>Tokens</ob-sectionheading>
      <sz-tokens-view
        .globalTokens=${globalTokens.map((t) => ({
          id: t.id,
          name: t.name,
          type: 'global' as const,
          createdAt: t.createdAt,
          lastUsed: t.lastUsed,
        }))}
        .ciTokens=${ciTokens.map((t) => ({
          id: t.id,
          name: t.name,
          type: 'ci' as const,
          service: t.service,
          createdAt: t.createdAt,
          lastUsed: t.lastUsed,
        }))}
        @create=${(e: CustomEvent) => {
          appstate.registriesStatePart.dispatchAction(appstate.createRegistryTokenAction, {
            token: {
              name: `new-${e.detail.type}-token`,
              type: e.detail.type,
              permissions: ['pull'],
            },
          });
        }}
        @delete=${(e: CustomEvent) => {
          appstate.registriesStatePart.dispatchAction(appstate.deleteRegistryTokenAction, {
            tokenId: e.detail.id || e.detail.tokenId,
          });
        }}
      ></sz-tokens-view>
    `;
  }
}
