File size: 2,409 Bytes
650485d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { Component, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatCardModule } from '@angular/material/card';
import { Subscription } from 'rxjs';

import { ApiService } from '../services/api.service';

interface ChatMessage {
  author: 'user' | 'assistant';
  text: string;
}

@Component({
  selector: 'app-chat',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatButtonModule,
    MatIconModule,
    MatFormFieldModule,
    MatInputModule,
    MatCardModule
  ],
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.scss']
})
export class ChatComponent implements OnDestroy {
  /** Backend’ten dönen oturum kimliği */
  sessionId: string | null = null;

  /** Sohbet geçmişi */
  messages: ChatMessage[] = [];

  /** Kullanıcı metni */
  input = this.fb.control('', Validators.required);

  /** Arkaplan istekleri için abonelikleri tutuyoruz */
  private subs = new Subscription();

  constructor(private fb: FormBuilder, private api: ApiService) {}

  /** <Start Chat> butonu */
  startChat(): void {
    const sub = this.api.startChat().subscribe({
      next: (res: any) => {
        this.sessionId = res.session_id;
      },
      error: () => {
        alert('Chat başlatılamadı - tekrar deneyin.');
      }
    });
    this.subs.add(sub);
  }

  /** <Send> butonu */
  send(): void {
    if (!this.sessionId || this.input.invalid) return;

    const text = this.input.value!.trim();
    if (!text) return;

    // Önce kullanıcı mesajını ekranda göster
    this.messages.push({ author: 'user', text });
    this.input.reset();

    const sub = this.api.chat(this.sessionId, text).subscribe({
      next: (res: any) => {
        this.messages.push({ author: 'assistant', text: res.text });
      },
      error: () => {
        this.messages.push({
          author: 'assistant',
          text: '❗️ Mesaj iletilemedi, lütfen tekrar deneyin.'
        });
      }
    });
    this.subs.add(sub);
  }

  ngOnDestroy(): void {
    this.subs.unsubscribe();
  }
}