import { Component, Injector, ViewEncapsulation, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UserPreferencesServiceProxy, UserPreferenceDto, UserServiceProxy, PreferencesServiceProxy } from '@shared/service-proxies/service-proxies';
import { NotifyService } from '@abp/notify/notify.service';
import { AppComponentBase } from '@shared/common/app-component-base';
import { TokenAuthServiceProxy } from '@shared/service-proxies/service-proxies';
import { CreateOrEditUserPreferenceModalComponent } from './create-or-edit-userPreference-modal.component';
import { ViewUserPreferenceModalComponent } from './view-userPreference-modal.component';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { Table } from 'primeng/components/table/table';
import { Paginator } from 'primeng/components/paginator/paginator';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { FileDownloadService } from '@shared/utils/file-download.service';
import * as _ from 'lodash';
import * as moment from 'moment';

@Component({
    templateUrl: './userPreferences.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class UserPreferencesComponent extends AppComponentBase {

    @ViewChild('createOrEditUserPreferenceModal', { static: true }) createOrEditUserPreferenceModal: CreateOrEditUserPreferenceModalComponent;
    @ViewChild('viewUserPreferenceModalComponent', { static: true }) viewUserPreferenceModal: ViewUserPreferenceModalComponent;
    @ViewChild('dataTable', { static: true }) dataTable: Table;
    @ViewChild('paginator', { static: true }) paginator: Paginator;

    advancedFiltersAreShown = false;
    filterText = '';
    maxUserIdFilter: number;
    maxUserIdFilterEmpty: number;
    minUserIdFilter: number;
    minUserIdFilterEmpty: number;
    valueFilter = '';
    maxPreferenceIdFilter: number;
    maxPreferenceIdFilterEmpty: number;
    minPreferenceIdFilter: number;
    minPreferenceIdFilterEmpty: number;

    filteredUser: any;
    filteredUserWithPreferences: any;
    filteredPreferences: any;
    preferenceId: number;
    userId: any;

    maxCount:number = 1000;


    constructor(
        injector: Injector,
        private _userPreferencesServiceProxy: UserPreferencesServiceProxy,
        private _notifyService: NotifyService,
        private _tokenAuth: TokenAuthServiceProxy,
        private _activatedRoute: ActivatedRoute,
        private _fileDownloadService: FileDownloadService,
        private _userServiceProxy: UserServiceProxy,
        private _preferencesServiceProxy: PreferencesServiceProxy
        
    ) {
        super(injector);
    }

    ngOnInit(){
        this.filterUser();
        this.filterUserWithPreferences();
        this.filterUserPreferences();
        $('.kt-select2').select2({ 
            placeholder: "Select.."
        });
    }

    getUserPreferences(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        this.spinnerService.show();
        this.preferenceId =  Number((<HTMLInputElement>document.getElementById('selectedPreferences')).value) ? Number((<HTMLInputElement>document.getElementById('selectedPreferences')).value) : undefined;
        this.userId =  Number((<HTMLInputElement>document.getElementById('selectedUser')).value) ? Number((<HTMLInputElement>document.getElementById('selectedUser')).value) : undefined;
        this._userPreferencesServiceProxy.getAll(
            this.filterText,
            this.userId,
            this.valueFilter,
            this.preferenceId,
            this.primengTableHelper.getSorting(this.dataTable),
            this.primengTableHelper.getSkipCount(this.paginator, event),
            this.primengTableHelper.getMaxResultCount(this.paginator, event)
        ).subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            console.log(result.items)
            this.spinnerService.hide();
        });
    }

    reloadPage(): void {
        this.paginator.changePage(this.paginator.getPage());
    }

    createUserPreference(): void {
        this.createOrEditUserPreferenceModal.show();
    }

    deleteUserPreference(userPreference: UserPreferenceDto): void {
        this.message.confirm(
            '',
            (isConfirmed) => {
                if (isConfirmed) {
                    this._userPreferencesServiceProxy.delete(userPreference.id)
                        .subscribe(() => {
                            this.reloadPage();
                            this.notify.success(this.l('SuccessfullyDeleted'));
                        });
                }
            }
        );
    }

    exportToExcel(): void {
        this._userPreferencesServiceProxy.getUserPreferencesToExcel(
            this.filterText,
            this.maxUserIdFilter == null ? this.maxUserIdFilterEmpty : this.maxUserIdFilter,
            this.minUserIdFilter == null ? this.minUserIdFilterEmpty : this.minUserIdFilter,
            this.valueFilter,
            this.maxPreferenceIdFilter == null ? this.maxPreferenceIdFilterEmpty : this.maxPreferenceIdFilter,
            this.minPreferenceIdFilter == null ? this.minPreferenceIdFilterEmpty : this.minPreferenceIdFilter,
        )
            .subscribe(result => {
                this._fileDownloadService.downloadTempFile(result);
            });
    }

    filterUser(): void {
        
        this._userServiceProxy.getUsers(
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            this.maxCount,
            undefined
        ).subscribe(result => {
            this.filteredUser = result.items;
        });
    }

    filterUserWithPreferences(): void {
        this._userPreferencesServiceProxy.getAll(
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            this.maxCount
        ).subscribe(result => {
            this.filteredUserWithPreferences = result.items;
            console.log(this.filteredUserWithPreferences);
        })
    }

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