import { Component, ViewChild, Injector, Output, EventEmitter} from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';
import { UserPreferencesServiceProxy, CreateOrEditUserPreferenceDto, PreferencesServiceProxy } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import * as moment from 'moment';


@Component({
    selector: 'createOrEditUserPreferenceModal',
    templateUrl: './create-or-edit-userPreference-modal.component.html'
})
export class CreateOrEditUserPreferenceModalComponent extends AppComponentBase {

    @ViewChild('createOrEditModal', { static: true }) modal: ModalDirective;


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

    active = false;
    saving = false;

    userPreference: CreateOrEditUserPreferenceDto = new CreateOrEditUserPreferenceDto();
    filteredPreferences: any;


    constructor(
        injector: Injector,
        private _userPreferencesServiceProxy: UserPreferencesServiceProxy,
        private _preferencesServiceProxy: PreferencesServiceProxy
    ) {
        super(injector);
    }
    ngOnInit(){
        this.filterUserPreferences();
    }

    show(userPreferenceId?: number): void {

        if (!userPreferenceId) {
            this.userPreference = new CreateOrEditUserPreferenceDto();
            this.userPreference.id = userPreferenceId;
            this.active = true;
            this.modal.show();
        } else {
            this._userPreferencesServiceProxy.getUserPreferenceForEdit(userPreferenceId).subscribe(result => {
                this.userPreference = result.userPreference;


                this.active = true;
                this.modal.show();
            });
        }
    }

    save(): void {
            this.saving = true;
            this.userPreference.preferenceId =  Number((<HTMLInputElement>document.getElementById('selectedPreference')).value) ? Number((<HTMLInputElement>document.getElementById('selectedPreference')).value) : null;
            this._userPreferencesServiceProxy.createOrEdit(this.userPreference)
             .pipe(finalize(() => { this.saving = false;}))
             .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
             });
    }







    close(): void {

        this.active = false;
        this.modal.hide();
    }

    filterUserPreferences(): void {
        this._preferencesServiceProxy.getAll(
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined
        ).subscribe(result => {
            this.filteredPreferences = result.items;
            console.log(this.filteredPreferences);
        });
      }
}
