import { Component, OnInit, AfterContentInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Infra } from '@overflow/commons-typescript/model/infra';
import { Store, select } from '@ngrx/store';
import { ListSelector } from 'packages/infra/store';
import * as InfraListStore from 'packages/infra/store/list';
import { Page, PageParams } from 'app/commons/model';
import { RPCClientError } from '@loafer/ng-rpc/protocol';
import { Probe } from '@overflow/commons-typescript/model/probe';

import { Target } from '@overflow/commons-typescript/model/target';
import { Subscription } from 'rxjs/Subscription';


@Component({
    selector: 'of-target-list',
    templateUrl: './list.component.html',
})
export class ListComponent implements OnInit, AfterContentInit, OnDestroy {

    infrasSubscription$: Subscription;
    infras$ = this.infraListStore.pipe(select(ListSelector.select('page')));
    infras: Infra[];
    probe: Probe;
    target: Target = null;
    sensorSettingDisplay = false;

    pageSize = '10';
    totalLength = 0;
    currPage = 0;

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private infraListStore: Store<InfraListStore.State>,
    ) {
    }

    ngOnInit() {
        this.infrasSubscription$ = this.infras$.subscribe(
            (page: Page) => {
                if (!page) {
                    return;
                }
                this.totalLength = page.totalElements;
                this.infras = page.content;
            },
            (error: RPCClientError) => {
                console.log(error);
            }
        );
    }

    ngAfterContentInit() {
        this.route.params.subscribe((params: any) => {
            this.probe = {
                id: params['id'],
            };
            this.getInfras(0);
        });
    }

    ngOnDestroy() {
        if (this.infrasSubscription$) {
            this.infrasSubscription$.unsubscribe();
        }
    }

    getInfras(pageNo) {
        const pageParams: PageParams = {
            pageNo: pageNo + '',
            countPerPage: this.pageSize,
            sortCol: 'id',
            sortDirection: 'descending'
        };
        this.infraListStore.dispatch(
            new InfraListStore.ReadAllByProbe(
                { probe: this.probe, pageParams: pageParams }
            )
        );
    }

    onRowSelect(event) {
        // this.router.navigate(['target'], { queryParams: { target: event.data.id } });
        this.router.navigate(['target', event.data.id, 'info']);
    }

    onAddSensor(target: Target) {
        this.target = target;
        this.sensorSettingDisplay = true;
    }

    onSensorSettingClose() {
        this.sensorSettingDisplay = false;
    }

    onPaging(e) {
        this.getInfras(e.page);
    }

}
