import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, tap } from 'rxjs/operators';
import { CourseModel } from '../model/course.model';

@Injectable({
  providedIn: 'root'
})
export class CourseService {
  url = environment.url
  createStatus: boolean = true
  constructor(private http: HttpClient) { }
  getListCourse(status?:string): Observable<CourseModel[]> {
    if(status){
      return this.http.get<CourseModel[]>(this.url + "course-center/upload/lists?status="+status)
      }else{
      return this.http.get<CourseModel[]>(this.url + "course-center/upload/lists")
    }
  }
  getCourseById(logId:string): Observable<CourseModel> {
    return this.http.get<CourseModel>(this.url + "course-center/upload/"+logId)
  }
  downloadFile(logId:string){
    return this.http.get<CourseModel>(this.url + "course-center/files/download/"+logId)
  }
  createCourse(model: CourseModel): Observable<boolean> {
    if (this.createStatus) {
      this.createStatus = false
      return this.http.post(this.url + 'course-center', model, { observe: 'response' })
        .pipe(
          tap(x => this.createStatus = true),
          map(r => r.status == 200)
        );
    } else {
      return of(false)
    }
  }
  deleteCourse(model: CourseModel): Observable<any> {
    let body = {
      logId: model.logId
    }
    let option = {
      headers: new HttpHeaders({
        "Content-Type": "application/json",
      }),
      body: body
    }
    return this.http.delete<any>(this.url + 'course-center/upload', option)
  }
  approve(model: CourseModel): Observable<any> {
    let body = {
      logId: model.logId,
      status: model.status
    }
    return this.http.put<any>(this.url + "course-center/approve",body)
  }
}
