import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import {Post} from '../models/post';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {AuthorWithPost} from '../models/author-with-post';
import {ConfigurationService} from '../configuration.service';

@Injectable({
  providedIn: 'root'
})
export class PostService {
  apiUrl: string = '';
  constructor(private httpClient: HttpClient,
              private configurationService: ConfigurationService) {
    this.apiUrl = `${this.configurationService.getApiUrl()}/posts`;
  }

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

  listWithAuthors(): Observable<AuthorWithPost[]> {
    return this.httpClient.get<AuthorWithPost[]>(`${this.apiUrl}/authors`);
  }

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

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

  updatePost(postId: bigint, postData: any, token: string) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Authorization': `Bearer ${token}`
      })
    };
    return this.httpClient.put(`${this.apiUrl}/${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.apiUrl, 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}`
        })
      };
      return this.httpClient.put<Post>(`${this.apiUrl}/${id}/illustration`, formData, httpOptions);
    } else {
      throw new Error('Image doesn\'t exist');
    }
  }
}
