<template>
  <div class="card overflow-y-hidden">
    <div class="card-header">
      <h5 class="card-title mb-0">Chat</h5>
    </div>
    <div class="card-body overflow-y-auto">
      <div class="overflow-y-auto">
        <div v-if="aiInstance.messages.length === 0">
          <i>No conversation history</i>
        </div>
        <div v-for="message in aiInstance.messages">
          <b>{{ message.name }}</b>{{ ': ' + message.content }}
        </div>
        <div v-if="waiting">
          <Spinner :style="'text-secondary'" :size="1"/>
        </div>
      </div>
    </div>
    <div class="card-footer">
      <div class="input-group">
        <input type="text" class="form-control" v-model="user" placeholder="Username" style="max-width: 10em"/>
        <input type="text" class="form-control" v-model="text" placeholder="Type message here" @keydown.enter="send"/>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {Options, Vue} from 'vue-class-component';
import {Prop} from 'vue-property-decorator';
import {toast} from 'vue3-toastify';
import {AiInstanceVmV1, ChatMessageVmV1} from 'ai-oas';
import {ApiStore} from '@/stores/ApiStore';
import Spinner from '@/components/Spinner.vue';

@Options({
  name: 'Chat',
  components: {
    Spinner,
  },
})
export default class Chat extends Vue {
  @Prop({required: true})
  readonly aiInstance!: AiInstanceVmV1;
  readonly apiStore = new ApiStore();
  user: string = 'alice';
  text: string = '';
  waiting: boolean = false;
  message: ChatMessageVmV1 | null = null;

  async send(): Promise<void> {
    this.waiting = true;
    try {
      this.message = ChatMessageVmV1.fromJson({'role': 'user', 'name': this.user, 'content': this.text});
      this.text = '';
      await this.apiStore.aiApi.chatText(this.aiInstance.configuration.id, this.message);
    } catch (e) {
      toast.error('Error while chatting: ' + JSON.stringify(e));
    } finally {
      this.waiting = false;
      this.message = null;
    }
  }
}
</script>
