import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from '../environments/environment';
import { MessageTemplateModel } from './models/message-template.model';
import { PlaceholderOptionsEnum } from './models/placeholder-options.enum';
import { TemplateTypeEnum } from './models/template-type.enum';
import { ApiService } from './oneit/services/api.service';
import { EnumService } from './oneit/services/enum.service';
import { SearchService } from './oneit/services/search.service';
import { UtilsService } from './oneit/services/utils.service';

@Injectable()

export class AppService {

    constructor(
        private enumService: EnumService,
        private searchService: SearchService,
        private utilsService: UtilsService,
        private apiService: ApiService
    ) {

    }

    getMessageTemplateTypeEnum(): Observable<Array<TemplateTypeEnum>> {
        return this.enumService.getEnums('TemplateTypes', true);
    }

    getPlaceholderOptionsEnum(): Observable<Array<PlaceholderOptionsEnum>> {
        return this.enumService.getEnumsWithNULLOptionLabel('PlaceholderOptions', 'Select variable');
    }

    getTypes(serviceName: string, includeNull = false, blankLabel = null): Observable<Array<any>> {
        return includeNull ? this.enumService.getEnumsWithNULLOptionLabel(serviceName, blankLabel) :
            this.enumService.getEnums(serviceName, true);
    }

    getSearchListing(serviceName: string, queryType: string, queryParams, assocs, searchName): Observable<Array<any>> {
        return this.searchService.searchAndSaveSearchRequest(serviceName, queryType,
            queryParams, assocs, null, null, null, null, searchName, false)
            .map(
                data =>
                    this.utilsService.convertResponseToObjects(data, assocs)
            );
    }

    getMessageTemplateByID(id, assocs): Observable<MessageTemplateModel> {
        return this.searchService.getObjectById('MessageTemplates', id, assocs)
            .map(
                data => {
                    const objs = this.utilsService.convertResponseToObjects(data, assocs);

                    if (objs && objs.length > 0) {
                        return objs[0];
                    }
                }
            );
    }

    processObjects(serviceName: string, dataParams): Observable<any> {
        const params: any = {
            environment: environment.envName,    // Fetch this from environment e.g. environment.envName
            ...dataParams
        };

        return this.apiService.post(`svc/${serviceName}`, params)
            .map(
                data => {
                    if (this.utilsService.isSuccessfulResponse(data)) {
                        return data;
                    }
                }
            );
    }
}
