import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpEvent, HttpRequest } from '@angular/common/http';

import { Post, Category, Image } from '../../core/entities';
import { environment } from '../../../environments/environment';

const IMAGES_URL = environment.apiUrl + '/api/images';
const POSTS_URL = environment.apiUrl + '/api/posts';
const CATEGORIES_URL = environment.apiUrl + '/api/categories';

@Injectable()
export class CreateUpdatePostService {

	constructor(private http: HttpClient) {}

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

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

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

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

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

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

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

		formData.append('file', file);

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

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