import { Component, OnInit, Output, EventEmitter, Input, AfterContentInit, OnChanges } from '@angular/core';
import { Router } from '@angular/router';
import { Target } from '@overflow/commons-typescript/model/target';
import { RPCClientError } from '@loafer/ng-rpc';
import { Domain } from '@overflow/commons-typescript/model/domain';
import { AuthSelector } from '@overflow/member/store';
import * as ListStore from '@overflow/infra/store/list';
import { ListSelector } from '@overflow/infra/store';
import { Store, select } from '@ngrx/store';
// import { Page, PageParams } from 'app/commons/model';
import { SelectItem } from 'primeng/primeng';

@Component({
    selector: 'of-target-selector',
    templateUrl: './target-selector.component.html',
})
export class TargetSelectorComponent implements OnInit, OnChanges {

    targets$ = this.store.pipe(select(ListSelector.select('page')));

    @Input() preTarget: Target = null;
    @Input() visible;
    @Output() targetSelected = new EventEmitter<Target>();
    targets: Target[] = null;

    constructor(
        private router: Router,
        private store: Store<ListStore.State>
    ) { }

    ngOnInit() {
        // this.targets$.subscribe(
        //     (page: Page) => {
        //         if (page !== null) {
        //             this.convertInfraToTarget(page);
        //         }
        //     },
        //     (error: RPCClientError) => {
        //         console.log(error.response.message);
        //     }
        // );
    }

    ngOnChanges(changes) {
        this.targets = [];
        if (this.preTarget === null) {
            this.getTargetList();
        } else {
            this.targets.push(this.preTarget);
            this.targetSelected.emit(this.preTarget);
        }
    }

    // convertInfraToTarget(page: Page) {
    //     for (const infra of page.content) {
    //         this.targets.push(infra.target);
    //     }
    // }

    getTargetList() {
        // this.store.select(AuthSelector.select('domain')).subscribe(
        //     (domain: Domain) => {
        //         const pageParams: PageParams = {
        //             pageNo: '0',
        //             countPerPage: '9999',
        //             sortCol: 'id',
        //             sortDirection: 'descending'
        //         };
        //         this.store.dispatch(new ListStore.ReadAllByDomain({ domain, pageParams }));
        //     },
        //     (error) => {
        //         console.log(error);
        //     }
        // );

        // Temporary data
        for (let i = 0; i < 10; i++) {
            const t: Target = {
                id: i,
                displayName: 'DisplayName' + i,
                createDate: new Date(),
                description: 'Description' + i,
            };
            this.targets.push(t);
        }
    }

    onSelectionChange(event) {
        this.targetSelected.emit(event.value[0]);
    }

}
