import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import {Post} from '../models/post';
import {HttpClient, HttpHeaders} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class PostService {
  url: string = 'http://localhost:8080/api/posts';
  constructor(private httpClient: HttpClient) {}

  list(): Observable<Post[]> {
    return this.httpClient.get<Post[]>(this.url);
  }

  getPost(id: bigint) {
    return this.httpClient.get<Post>(`${this.url}/${id}`);
  }

  deletePost(id: bigint, token: string) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Authorization': `Bearer ${token}`
      })
    };
    return this.httpClient.delete(`${this.url}/${id}`, httpOptions);
  }

  updatePost(postId: bigint, postData: any, token: string) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Authorization': `Bearer ${token}`
      })
    };
    return this.httpClient.put(`${this.url}/${postId}`, postData, httpOptions);

  }

  createPost(post: any, token: string | undefined): Observable<Post> {
    const httpOptions = {
      headers: new HttpHeaders({
        'Authorization': `Bearer ${token}`
      })
    };
    return this.httpClient.post<Post>(this.url, post, httpOptions);
  }

  changeIllustration(id: bigint | undefined, image: File | undefined, token: string): Observable<Post> {
    if (image) {
      const formData: FormData = new FormData();
      formData.append('illustration', image);
      const httpOptions = {
        headers: new HttpHeaders({
          'Authorization': `Bearer ${token}`
        })
      };
      console.log(image);
      return this.httpClient.put<Post>(`${this.url}/${id}/illustration`, formData, httpOptions);
    } else {
      throw new Error('Image doesn\'t exist');
    }
  }
}
