import { Component, OnInit, AfterViewInit, AfterContentInit, Input } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Infra } from 'packages/infra/model';
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 'packages/probe/model';

import * as ProbeDetailStore from 'packages/probe/store/detail';
import { DetailSelector as ProbeDetailSelector } from 'packages/probe/store';
import { Target } from '../../model';


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

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

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

    ngOnInit() {

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

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

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

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

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

    onSensorSettingClose() {
        this.sensorSettingDisplay = false;
    }

}
