import { LitElement, html, css, property, customElement } from './plugins.js';
import type { CSSResult, TemplateResult } from './plugins.js';
import { sharedStyles, tableStyles } from './sw-dash-styles.js';
import { SwDashTable } from './sw-dash-table.js';
import type { IColumnConfig } from './sw-dash-table.js';

export interface ICachedResource {
  url: string;
  domain: string;
  contentType: string;
  size: number;
  hitCount: number;
  missCount: number;
  lastAccessed: number;
  cachedAt: number;
  hitRate?: number;
}

/**
 * URLs table view component
 */
@customElement('sw-dash-urls')
export class SwDashUrls extends LitElement {
  public static styles: CSSResult[] = [
    sharedStyles,
    tableStyles,
    css`
      :host {
        display: block;
      }
    `
  ];

  @property({ type: Array }) accessor resources: ICachedResource[] = [];

  private columns: IColumnConfig[] = [
    { key: 'url', label: 'URL', className: 'url' },
    { key: 'contentType', label: 'Type' },
    { key: 'size', label: 'Size', className: 'num', formatter: SwDashTable.formatBytes },
    { key: 'hitCount', label: 'Hits', className: 'num', formatter: SwDashTable.formatNumber },
    { key: 'missCount', label: 'Misses', className: 'num', formatter: SwDashTable.formatNumber },
    { key: 'hitRate', label: 'Hit Rate' },
    { key: 'lastAccessed', label: 'Last Access', formatter: SwDashTable.formatTimestamp },
  ];

  private getDataWithHitRate(): ICachedResource[] {
    return this.resources.map(r => {
      const total = r.hitCount + r.missCount;
      return {
        ...r,
        hitRate: total > 0 ? Math.round((r.hitCount / total) * 100) : 0
      };
    });
  }

  public render(): TemplateResult {
    return html`
      <sw-dash-table
        .columns="${this.columns}"
        .data="${this.getDataWithHitRate()}"
        filterPlaceholder="Filter URLs..."
        infoLabel="resources"
      ></sw-dash-table>
    `;
  }
}
