import {AvailableMods} from "../core/api";
import React, {useEffect, useState} from "react";
import {NavLink} from "react-router-dom";
import {IMod} from "../types/Imod";

function Mods (mods: IMod[]) {

    let mapWithModVersions: Map<String, IMod[]> = new Map();

    mods.forEach( mod => {
        const versionList = mapWithModVersions.get(mod.name)
      if(versionList == null){
          mapWithModVersions.set(mod.name, new Array(mod))
      } else {
          versionList.push(mod)
      }
    })



    function Mod (modName: String) {
        let sameMods = mapWithModVersions.get(modName) ?? []

        let lastBeta = sameMods.filter((m) => m.isBeta).reverse()[0]

        return(
            <div>
                <h1>{modName}</h1>

                {sameMods.filter((m) => !m.isBeta).map(mod =>
                    <ul><NavLink state={mod.id} to= {"/mod/" + mod.id} >{mod.version}</NavLink></ul>)}
                {sameMods.find((m) => m.isBeta) != null && <div><i>Beta versions:</i></div>}
                {lastBeta != null &&
                    <ul><NavLink state={lastBeta.id} to={"/mod/" + lastBeta.id}>{lastBeta.version}</NavLink></ul>
                    }
            </div>
        )
    }

    return(
        [...mapWithModVersions.keys()].map(m => Mod(m))
    )
}

interface ModsPageState {
    mods: IMod[]
}

class ModsPage extends React.Component<any, ModsPageState> {

    constructor({props}: { props: any }) {
        super(props);
        this.state = {
            mods: []
        }
    }

    async componentDidMount() {
        const response = await fetch(AvailableMods);
        const data: IMod[] = await response.json();
        console.log(data);
        this.setState({
            mods : data
        });
    }

    render() {
        return <div>{Mods(this.state.mods)}</div>;
    }
}

export default ModsPage