import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { catchError, Observable, of, tap } from "rxjs";
import { Subject } from "./subject.model";
import { Student } from "../students/student.model";

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

export interface Changeset {
  records: [],
}

@Injectable({
  providedIn: 'root'
})
export class SubjectService {

  private subjectsUrl = 'http://localhost:8080/subjects';

  constructor(private http: HttpClient) { }

  getSubjects(): Observable<Subject[]> {
    return this.http.get<Subject[]>(this.subjectsUrl);
  }

  getSubject(id: number): Observable<Subject> {
    const url = `${this.subjectsUrl}/${id}`;
    return this.http.get<Subject>(url);
  }

  addSubject(subject: Subject): Observable<Subject> {
    return this.http.post<Subject>(this.subjectsUrl, subject, httpOptions).pipe(
      tap((subjectAdded: Subject) => this.log(`added subject id=${subjectAdded.id}`)),
      catchError(this.handleError<Subject>('addSubject'))
    )
  }

  deleteSubjects(subjects: Subject[]): Observable<any> {
    const ids = subjects.map(subject => subject.id);
    return this.http.post(`${this.subjectsUrl}/delete`, {records: ids}, httpOptions);
  }

  addStudentToSubject(subject: Subject, ids: Number[]): Observable<any> {
    return this.http.patch(`${this.subjectsUrl}/${subject.id}`, {studentAssoc: ids}, httpOptions);
  }

  // removeStudentFromSubject(subject: Subject, student: Student): Observable<any> {
  //
  // }

  private log(message: string): void {
    console.log('SubjectService: ' + message);
  }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.log(error);
      this.log(`${operation} failed: ${error.message}`);
      return of(result as T);
    }
  }
}
