import { Injectable, Inject, LOCALE_ID } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Pergunta, Questionario, TemaPergunta } from '../models/questionario.model';

@Injectable({
  providedIn: 'root'
})
export class QuestionarioService {
  private readonly BASE_URL = 'http://localhost:8080';
  private readonly httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    }),
    withCredentials: true
  };

  constructor(
    private httpClient: HttpClient,
    @Inject(LOCALE_ID) public locale: string
  ) { }

  listarQuestionarios(): Observable<Questionario[]> {
    return this.httpClient.get<Questionario[]>(`${this.BASE_URL}/listaquestionarios`, this.httpOptions);
  }

  listarTemas(): Observable<TemaPergunta[]>{
    return this.httpClient.get<TemaPergunta[]>(`${this.BASE_URL}/listartemapergunta`);
  }

  adicionaTema(tema: string): Observable<void>{
    const novoTema: TemaPergunta = { tema: tema };
    return this.httpClient.post<void>(`${this.BASE_URL}/novotema`, novoTema, {...this.httpOptions});
  }

  inserirQuestionario(questionario: Questionario): Observable<Questionario> {
    return this.httpClient.post<Questionario>(`${this.BASE_URL}/novoquestionario`, questionario, { ...this.httpOptions, responseType: 'text' as 'json' });
  }

  atualizarQuestionario(questionario: Questionario): Observable<any> {
    return this.httpClient.put<any>(`${this.BASE_URL}/editarquestionario/${questionario.id}`, questionario, this.httpOptions);
  }

  removerQuestionario(id: number): Observable<any> {
    return this.httpClient.delete<any>(`${this.BASE_URL}/removerquestionario/${id}`, this.httpOptions);
  }

  buscarPorId(id: number): Observable<Questionario> {
    return this.httpClient.get<Questionario>(`${this.BASE_URL}/questionario/${id}`, this.httpOptions);
  }

  listarPerguntas(): Observable<any[]> {
    return this.httpClient.get<any[]>(`${this.BASE_URL}/listaperguntas`, this.httpOptions);
  }
 
  cadastrarNovaPergunta(pergunta: any): Observable<any> {
    return this.httpClient.post<any>(`${this.BASE_URL}/novapergunta`, pergunta, this.httpOptions);
  }

  listarQuestionariosPorFuncionario(funcId: number): Observable<Questionario[]> {
    const params = new HttpParams().set('funcId', funcId.toString());
    return this.httpClient.get<Questionario[]>(`${this.BASE_URL}/questionarios`, { ...this.httpOptions, params });
  }

  enviarRespostas(surveyId: number, funcId: number, respostas: any[]): Observable<any> {
    const params = new HttpParams()
      .set('surveyId', surveyId.toString())
      .set('funcId', funcId.toString());

    return this.httpClient.post(`${this.BASE_URL}/questionario/resposta`, respostas, { ...this.httpOptions, params , responseType:'text'});
  }

}
