import { Injectable } from '@angular/core';
import { HttpClient, HttpEvent, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Post, Category, Image } from '../../core/entities';

@Injectable()
export class CreateUpdatePostService {

	constructor(private http: HttpClient) {}

	processPreview(post: Post): Observable<Post> {
		return this.http.post<Post>(`/api/posts/preview`, post);
	}

	getCategories(): Observable<Array<Category>> {
		return this.http.get<Array<Category>>(`/api/categories/`);
	}

	addPost(post: Post): Observable<Post> {
		return this.http.post<Post>(`/api/posts/`, post);
	}

	updatePost(post: Post): Observable<Post> {
		return this.http.put<Post>(`/api/posts/`, post);
	}

	getPost(postKey: string): Observable<Post> {
		return this.http.get<Post>(`/api/posts/${postKey}/source`);
	}

	getImages(): Observable<Array<Image>> {
		return this.http.get<Array<Image>>(`/api/images/myImages`);
	}

	uploadPicture(file: File): Observable<HttpEvent<{}>> {
		const formData: FormData = new FormData();

		formData.append('file', file);

		return this.http.request(new HttpRequest(
			'POST', '/api/images', formData, {
				reportProgress: true,
				responseType: 'text'
			}
		));
	}

	getImageDetails(imageLink: string): Observable<Image> {
		return this.http.get<Image>(`/api/images/${imageLink}/details`);
	}
}
