import { Injectable } from '@angular/core';
import { HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

import { ApiService } from './api.service';
import { Application, ApplicationListConfig, ApplicationListFilters } from 'src/app/core/models';
import { map } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class ApplicationsService {
    constructor(
        private apiService: ApiService
    ) { }

    query(config: ApplicationListConfig): Observable<{ applications: Application[], applicationsCount: number }> {
        // Convert any filters over to Angular's URLSearchParams
        const params: ApplicationListFilters = {
            apikey: config.filters.apikey,
            author: config.filters.author,
            limit: config.filters.limit,
            offset: config.filters.offset
        };
        return this.apiService
            .get(
                '/applications' + ((config.type === 'feed') ? '/feed' : ''),
                new HttpParams({ fromObject: <any>params })
            );
    }

    get(slug: string): Observable<Application> {
        return this.apiService.get(`/applications/${slug}`)
            .pipe(map(data => data.application));
    }

    destroy(slug: string) {
        return this.apiService.delete(`/applications/${slug}`);
    }

    save(application: Application): Observable<Application> {
        if (application.slug) {
            // If we're updating an existing application
            return this.apiService.put(`/applications/${application.slug}`, { application: application })
                .pipe(map(data => data.application));
        } else {
            // Otherwise, create a new application
            return this.apiService.post('/applications/', { application: application })
                .pipe(map(data => data.application));
        }
    }

}
