import { Component, OnInit,
    ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core'

import { Subject, timer } from 'rxjs'
import { map } from 'rxjs/operators'
import { WebSocketSubject } from 'rxjs/webSocket'

import { SchedulerService, Job, JobEvent } from './scheduler.service'

@Component({
    selector: 'gisaf-admin-scheduler-messages',
    templateUrl: './messages.component.html',
    styleUrls: ['./messages.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    providers: [
        SchedulerService,
    ],
})
export class AdminSchedulerMessagesComponent implements OnInit {
    status: string = 'Not initialised'
    msgs: string[] = []
    timeDelta: number  // Time delta between browser and scheduler (positive: )
    time: Date

    constructor(
        private cdr: ChangeDetectorRef,
        protected schedulerService: SchedulerService,
    ) {}

    ngOnInit() {
        this.status = 'Connecting...'
        this.getTime()
        let onOpenSubject = new Subject()
        let onCloseSubject = new Subject()
        onOpenSubject.subscribe(
            res => {
                this.status = 'Connected'
                this.cdr.markForCheck()
            }
        )
        onCloseSubject.subscribe(
            (res: CloseEvent) => {
                this.status = 'Disconnected - reason: ' + res.reason || res.code.toString() || 'unknown'
                this.cdr.markForCheck()
            }
        )

        let ws: WebSocketSubject<object> = this.schedulerService.connect(onOpenSubject, onCloseSubject)
        let foo = ws.next({
            'message': 'subscribe',
        })
        ws.subscribe(
            data => {
                this.msgs.push(data['msg'])
                this.cdr.markForCheck()
            }
        )
    }

    getTime() {
        // Get the time of the scheduler and set the running clock
        this.schedulerService.getTime().subscribe(
            serverTime => {
                // Approximate the network latency: rountrip time
                this.timeDelta = (serverTime.getTime() - new Date().getTime()) / 2 + 10
                // Just an approximate running clock for the user
                timer(1000, 1000).subscribe(
                    _ => {
                        this.time = new Date(new Date().getTime() - this.timeDelta)
                        this.cdr.markForCheck()
                    }
                )
            }
        )
    }
}
