<script lang="ts">
  import {GetModpacks, GetModpack} from '../wailsjs/go/main/ModpackManager.js'
	import {InstallVanilla, LaunchInstance, GetInstances, CheckUpdate} from '../wailsjs/go/main/InstanceManager.js'
	import {GetVersions} from '../wailsjs/go/main/App.js'
	import {onMount} from 'svelte'
	import {loading} from './global.ts'
	import {slide} from 'svelte/transition'

  let modpacks: string[] = []
	let pack: string
	let instances: Instance[] = []
	let instance: string
	let addingInstance: boolean = false
	let name: string = "New Modpack"

	function updateLists(){
		GetVersions().then((result) => {
				modpacks = result
				pack = modpacks[0]
				name = modpacks[0]
		})
		GetInstances().then((result) => {
			instances = result
			instance = instances[0].InstanceName
		})
	}

  onMount(() => {
		updateLists()
	})

	function onclick(event) {
		$loading = true
		LaunchInstance(instance).then(() => {
			$loading = false
			window.runtime.Quit()
		})
	}

	function install(){
		$loading = true
		InstallVanilla(pack, name).then(() => {
			addingInstance = false
			$loading = false
			updateLists()
		})
	}

	function onchange(event){
		name = event.target.value
	}


</script>

<main>
  <select bind:value={instance} name="pack">Select a Modpack: 
		{#each instances as instance}
				<option value={instance.InstanceName}>{instance.InstanceName}</option>
		{/each}
  </select>
	<button on:click={onclick}>Launch</button>
	<br/>
	{#if addingInstance}
		<div transition:slide="{{duration:300}}">
			<select id="pack" on:change={onchange} bind:value={pack} name="pack">Select a Modpack: 
				{#each modpacks as pack}
					<option value={pack}>{pack}</option>
				{/each}
			</select>
			<br/>
			<input bind:value={name} />
			<br/>
			<button on:click={install}>Install</button>
			<button on:click={() => {addingInstance = false}}>Cancel</button>
		</div>
	{:else}
		<button on:click={() => {addingInstance = true}}>Add Instance</button>
	{/if}
</main>

<style>
</style>
