<script>
    import Form from '$lib/components/Form.svelte';
    import { dev } from '$app/environment';
   
    let newhub, joinhub;
    let popup = "nodisplay";
    let hubJson = [];

    function openForm() {
        popup = '';
    }

    function closeForm() {
        popup = 'nodisplay';
    }

    let upload;
    let icon = '/img/logo.svg';

    function changeProfile(e) {
        upload.dispatchEvent(new MouseEvent('click'));
    }

    function newIcon(e) {
        icon = URL.createObjectURL(upload.files[0]);
    }

    function submitFunc(e, url, form) {
        e.preventDefault();
        const dataArray = new FormData(e.submitter.parentElement.parentElement);
        for (const file of upload.files) {
            dataArray.append('img', file);
        }
        fetch(url, {
            method: 'POST',
            body: dataArray
        });
        closeForm();
    }

    async function main() {
        if (dev) {
            var hubFetch = await fetch('http://localhost:5173/api/hub/list',{method: 'POST'});
        } else {
            var hubFetch = await fetch('https://allof.space/api/hub/list',{method: 'POST'});
        }
        try {
            hubJson = await hubFetch.json();
        } catch(error) {
        }
    }

    main();

</script>

<div class='content-wrapper'>
    <div class='content-main'>
        <h1><div class='button-section sbig'>
            Your Hubs
            <a href='#'><img src="/img/new.svg" class="icon-player" on:click={openForm}></a>
        </div>
        {#each hubJson as hubEntry}
                <a href='#'><img src="/api/hub/img?q={hubEntry.hub}" class="icon-hub pfp"></a>
        {/each}
        </h1>
    </div>
    <div class='content-main'>
        <slot />
    </div>
    <div class='content-main'>
        <h1><div class='button-sections sbig'>
            Directories
        </div></h1>
    </div>
</div>

<div class='popup {popup}' on:click|self={closeForm}> 
    <Form params="{[
        {
            "type": "text",
            "name": 'name',
            'desc': 'Name of hub'
        }
    ]}" submit='{(e) => submitFunc(e,"/api/hub/new")}' action='/api/hub/new' id='newhub' header="Create a hub...">
        <input slot='extraInfo' form='newhub' type='file' accept='image/png' name='img' on:change='{newIcon}' bind:this='{upload}'>

        <img src="{icon}" align='right' class="image-inline pfp" on:click={changeProfile}>
    </Form>


    <Form params="{[
        {
            "type": "text",
            "name": 'invite',
            'desc': 'Invite code'
        }
    ]}"  submit='{(e) => submitFunc(e,"/api/hub/join")}' bind:this='{joinhub}' action='/api/hub/join' header="Or join a hub">
    </Form>

</div> 
