import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

import { SearchService } from './search.service';
import { UtilsService } from './utils.service';

@Injectable()
export class EnumService {

    constructor(
        private searchService: SearchService,
        private utilsService: UtilsService,
    ) {

    }

    getEnums(enumName, onlyEnabled: boolean = false): Observable<any> {
        return this.searchService.getObjects(enumName, "All", {}, [], null, null, null, null, { onlyEnabled: onlyEnabled })
            .map(
                data => {
                    if (this.utilsService.isSuccessfulResponse(data)) {
                        return data.results;
                    }
                }
            );
    }

    getEnumsWithNULLOption(enumName: string, onlyEnabled: boolean = false): Observable<any> {
        return this.getEnumsWithNULLOptionLabel(enumName, 'Please Select', onlyEnabled);
    }

    getEnumsWithNULLOptionLabel(enumName: string, blankLabel: string, onlyEnabled: boolean = false): Observable<any> {
        return this.getEnums(enumName, onlyEnabled)
            .map(
                data => {
                    this.addNULLOptionForEnumSelectWithLabel(data, blankLabel);
                    return data;
                }
            );
    }

    addNULLOptionForEnumSelect(options: any[]) {
        return this.addNULLOptionForEnumSelectWithLabel(options, 'Please Select');
    }

    addNULLOptionForEnumSelectWithLabel(options: any[], blankLabel: string, fieldName: string = 'Description') {
        return this.utilsService.addNULLOptionForSelectWithLabel(options, fieldName, 'Value', blankLabel);
    }

    filterEnums(event, allEnums: any[], keyName:string = 'Description'):Observable<any[]> {
        let enums = [];
        if (allEnums) {
            for (let i = 0; i < allEnums.length; i++) {
                let enumObj = allEnums[i];
                if (enumObj) {
                    if( event.query && event.query.length > 0) {
                        if (enumObj[keyName].toLowerCase().indexOf(event.query.toLowerCase()) >= 0) {
                            enums.push(enumObj);
                        }
                    } else {
                        enums.push(enumObj);    //return all objects when filter string is empty.
                    }
                }
            }
        }
        return of(enums);
    }
}