import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, Inject } from '@angular/core';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { UxService } from '@eui/core';
import { CONFIG_TOKEN } from '@eui/core';

import { User } from './user.model';

@Injectable()
export class ApiService {

    private _apiConfig = this.config.modules;

    constructor(
        @Inject(CONFIG_TOKEN) protected config: any,
        private http: HttpClient,
        private uxService: UxService,
    ) {}

    users_getAll(): Observable<User[]> {
        const url = `${this._apiConfig.users.api.base}${this._apiConfig.users.api.users}`;

        return this.http.get<User[]>(url).pipe(
            catchError(this.handleError<User[]>()),
        );
    }

    users_getAllByNameLike(name: any): Observable<Array<User>> {
        const url = `${this._apiConfig.users.api.base}${this._apiConfig.users.api.users}/?name_like=${name}`;

        return this.http.get<User[]>(url).pipe(
            catchError(this.handleError<User[]>()),
        );
    }

    users_getById(id: number): Observable<User> {
        const url = `${this._apiConfig.users.api.base}${this._apiConfig.users.api.users}/${id}`;

        return this.http.get<User>(url).pipe(
            catchError(this.handleError<User>()),
        );
    }

    users_getPaginatedResponse(page: number = 1, size: number = 10) {
        const url = `${this._apiConfig.users.api.base}${this._apiConfig.users.api.users}`;

        const params = new HttpParams({
            fromString: `_page=${page}&_limit=${size}`,
        });

        return this.http.get(url, { params: params }).pipe(catchError(this.uxService.handleError));
    }

    posts_getPaginatedResponse(page: number = 1, size: number = 10) {
        const url = `${this._apiConfig.users.api.base}${this._apiConfig.users.api.users}`;

        const params = new HttpParams({
            fromString: `_page=${page}&_limit=${size}`,
        });

        return this.http.get(url, { params: params }).pipe(catchError(this.uxService.handleError));
    }

    private handleError<T>(operation = 'operation', result?: T) {
        return (error: any): Observable<T> => {
            console.error(error); // log to console instead
            return of(result as T);
        };
    }

}
