import $ from "jquery";
import * as JSX from "./jsx";
import { Page, Spinner } from "./components";
import { FtpEntry, ftpGetEntries, sizeHumanReadable } from "./util";

let entries: FtpEntry[] = [];
function urlForHref( href: string, isdir: boolean ) {
  const url = new URL( window.location.href );
  let path = url.pathname;
  if( isdir ) {
    if( path.endsWith( '/' ) ) {
      return path + href;
    }
    return path + "/" + href;
  }

  path = path.slice( path.indexOf( '/pkgs' ) + 5 );
  if( path.endsWith( '/' ) )
    return "https://networkheaven.net/pkgs" + path + href;
  else
    return "https://networkheaven.net/pkgs" + path + "/" + href;
}


function PackageEntry( props: any ) {
  const entry = props.entry as FtpEntry;
  const small = !!( window.innerWidth < 750 );
  return <tr>
    <td>
      { entry.name == "../" &&
      <a href='#' onclick={ () => JSX.goUpDirectory() } class="package-entry-link">
        ../
      </a> }
      { entry.name != "../" && !entry.isdir &&
      <a href={urlForHref( entry.name, entry.isdir )} class="package-entry-link">
        {entry.name}
      </a> }
      { entry.name != "../" && entry.isdir &&
      <a href='#' onclick={ () => JSX.navigate( urlForHref( entry.name, entry.isdir ) ) } class="package-entry-link">
        {entry.name}
      </a> }
    </td>
    <td><span class="package-entry-date">{entry.date}</span></td>
    <td><span class="package-entry-time">{entry.time}</span></td>
    <td>{ !entry.isdir && <span>{ sizeHumanReadable( parseInt( entry.size ), small ) }</span> }
        { entry.isdir  && <span>dir</span> }
    </td>
  </tr>
}

function getEndpoint() {
  const url = new URL( window.location.href );
  let href = url.pathname.split( "/pkg" )[1];

  if( href[0] == '/' ) {
    href = href.slice( 1 );
  }

  return "pkgs/" + href;
}

export default function Pkgs() {
  entries = [];
  setTimeout( async () => {
    const url = new URL( window.location.href );
    const showBack = !url.pathname.endsWith( "/pkg/" ) && !url.pathname.endsWith( "/pkg" );
    entries = await ftpGetEntries( getEndpoint(), showBack );

    const target = $( "#package-entries" ).find( "table" );
    $( "#package-entries" ).find( ".spinner" ).remove();
    target.empty();

    for( const entry of entries ) {
      target.append( <PackageEntry entry={entry} /> );
    }
  } );

  return <Page>
    <div class="page-title">
      <h3 style="font-family: JPN24; width: max-content" class="gradient">PACKAGE&nbsp;REPOSITORY</h3>
    </div>
    <hr />

    <div id="package-entries">
      <table style="width: 90%;" />
      <Spinner />
    </div>
  </Page>
}
