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

function downloadFile( file: string ) {
  const a = document.createElement( "a" );
  a.href = "https://networkheaven.net/pkgs/";
  a.download = "string";
  a.click();
  a.remove();
}

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

  let searchParams = url.searchParams.toString();
  searchParams = searchParams.slice( searchParams.indexOf( '/' ) );
  searchParams = searchParams.slice( searchParams.indexOf( '/' ) );
  return "https://networkheaven.net/pkgs" + searchParams + "/" + href;
}

interface PkgEntry {
  name: string;
  date: string;
  time: string;
  size: string;
  isdir: boolean;
}

function entryFromLine( line: string ): PkgEntry | null {
  const isdir = line[line.length - 1] == '-';
  const name = line.slice( 0, line.indexOf( " " ) );
  if( name == ".." ) return null;
  if( !name )
    return null;
  let date = '';
  let time = '';
  let size = ''
  
  if( !isdir ) {
    let end = line.lastIndexOf( " " );
    size = line.slice( end + 1 );
    date = line.slice( line.indexOf( " " ) + 1, end );
    end = date.indexOf( " " );
    const datetime = date.slice( date.search( /[0-9]/ ) );
    end = datetime.indexOf( ' ' );
    date = datetime.slice( 0, end );
    time = datetime.slice( end + 1 );
    time = time.slice( 0, time.indexOf( " " ) );
  } else {
    let start = line.search( /[0-9]/ )
    date = line.slice( start );
    let end = date.indexOf( " " );
    date = date.slice( 0, end );
    time = line.slice( start + end + 1, line.length - 1 );
    time = time.slice( 0, time.indexOf( " " ) );
  }

  return { name, date, time, size, isdir };
}

async function getEntries(): Promise<PkgEntry[]> {
  const url = new URL( window.location.href );
  const href = url.pathname.split( "/pkg" )[1];

  const packages = await fetch( "https://networkheaven.net/pkgs/" + href );
  const text = await packages.text();

  const pkgBody = $( <div /> );
  pkgBody.html( text );
  pkgBody.html( pkgBody.find( "body" ).html() );
  const pre = pkgBody.find( "pre" )[0].innerText;

  const ret = [];
  console.log( url.pathname );
  if( !url.pathname.endsWith( "/pkg/" ) && !url.pathname.endsWith( "/pkg" ) ) {
     ret.push({
      name: '../',
      date: ' ',
      time: ' ',
      size: '',
      isdir: true
    } );
  }

  const lines = pre.split( "\n" );
  for( const line of lines ) {
    if( !line.length )
      continue;

    const entry = entryFromLine( line );
    console.log( entry );
    if( entry )
      ret.push( entry );
  }

  return ret;
}

function back() {
  const url = new URL( window.location.href );
  if( url.pathname.endsWith( "/" ) )
    url.pathname = url.pathname.slice( 0, -1 );
  url.pathname = url.pathname.slice( 0, url.pathname.lastIndexOf( "/" ) );
  JSX.navigate( url.pathname );
}

function PackageEntry( props: any ) {
  console.log( props );
  const entry = props.entry as PkgEntry;
  console.log( urlForHref( entry.name, entry.isdir ) );
  return <tr>
    <td>
      { entry.name == "../" &&
      <a href='#' onclick={ () => back() } class="package-entry-link">
        ../
      </a> }
      { entry.name != "../" &&
      <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 ) ) }</span> }</td>
  </tr>
}

export default function Pkgs() {
  setTimeout( async () => {
    try {
      const entries = await getEntries();
      const target = $( "#package-entries" ).find( "table" );
      $( "#package-entries" ).find( ".spinner" ).remove();
      for( const entry of entries ) {
        target.append( <PackageEntry entry={entry} /> );
      }

    } catch( e ) {
      console.log( e );
    }

  } );

  return <Page>
    <div style="display: flex; justify-content: center">
      <h3 style="font-family: JPN24; font-size: 25px; width: min-content" class="gradient">PACKAGE&nbsp;REPOSITORY</h3>
    </div>
    <hr />

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