import {EventEmitter, Output} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {Observable} from 'rxjs/index';
import {isNullOrUndefined} from 'util';
import {catchError} from 'rxjs/internal/operators';
import {ApiBase} from './api-base';
import {environment} from '../../../environments/environment';


export class ResourceBase extends ApiBase {

	baseUrl = environment.API;
	private url = '';

	constructor(public http: HttpClient, private urlReceive: string) {
		super();
		this.url = this.baseUrl + urlReceive;
	}

	@Output() errorEvent: EventEmitter<any> = new EventEmitter(true);

	public index(page?: string, searchText?: string, sortBy?: string, order?: string, perPage?: string, visible?: string, deleted_at?: string): Observable<any> {

		const params = new HttpParams()
			.set('sortBy', isNullOrUndefined(sortBy) ? '' : sortBy)
			.set('order', isNullOrUndefined(order) ? '' : order)
			.set('page', isNullOrUndefined(page) ? '1' : page)
			.set('perPage', isNullOrUndefined(perPage) ? '10' : perPage)
			.set('visible', isNullOrUndefined(visible) ? '1' : visible)
			.set('deleted', isNullOrUndefined(deleted_at) ? '0' : deleted_at)
			.set('query', searchText ? searchText : '');
		const options = {params: params};

		return this.http.get(this.url, options).pipe(
			catchError(this.handleError('index'))
		);
	}


	public create(body: any): Observable<any> {
		return this.http.post(this.url, body).pipe(
			catchError(this.handleError('create'))
		);
	}

	public delete(id: number, reactivate = false): Observable<any> {

		let deleted = reactivate ? '?deleted=1' : '';

		return this.http.delete(`${this.url}/${id}`+ deleted).pipe(
			catchError(this.handleError('delete'))
		);
	}

	public show(id: number): Observable<any> {
		return this.http.get(`${this.url}/${id}`).pipe(
			catchError(this.handleError('show'))
		);
	}

	public update(id: number, body: any): Observable<any> {
		return this.http.put(`${this.url}/${id}`, body).pipe(
			catchError(this.handleError('update'))
		);
	}
}
