<template>
    <div class="character-groups">
        <div v-show="loading" class="alert alert-info">Loading groups.</div>
        <template v-if="!loading">
            <div class="character-group" v-for="group in groups" :key="group.id">
                <a :href="groupUrl(group)">{{group.title}}: {{group.threadCount}}</a>
            </div>
        </template>
        <div v-if="!loading && !groups.length" class="alert alert-info">No groups.</div>
    </div>
</template>

<script lang="ts">
    import Vue from 'vue';
    import Component from 'vue-class-component';
    import {Prop} from 'vue-property-decorator';
    import * as Utils from '../utils';
    import {methods} from './data_store';
    import {Character, CharacterGroup} from './interfaces';

    @Component
    export default class GroupsView extends Vue {
        @Prop({required: true})
        private readonly character: Character;
        private shown = false;
        groups: CharacterGroup[] = [];
        loading = true;
        error = '';

        groupUrl(group: CharacterGroup): string {
            return `${Utils.staticDomain}threads/group/${group.id}`;
        }

        async show(): Promise<void> {
            if(this.shown) return;
            try {
                this.error = '';
                this.shown = true;
                this.loading = true;
                this.groups = await methods.groupsGet(this.character.character.id);
            } catch(e) {
                this.shown = false;
                if(Utils.isJSONError(e))
                    this.error = <string>e.response.data.error;
                Utils.ajaxError(e, 'Unable to load groups.');
            }
            this.loading = false;
        }
    }
</script>