"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@angular/core");
const http_1 = require("@angular/http");
const material_1 = require("@angular/material");
const moment = require("moment");
const BehaviorSubject_1 = require("rxjs/BehaviorSubject");
const env_1 = require("../util/env");
const memorizingSubject_1 = require("../util/memorizingSubject");
const report_issue_1 = require("../util/report-issue");
var State;
(function (State) {
    State[State["LoggingIn"] = 0] = "LoggingIn";
    State[State["Loading"] = 1] = "Loading";
    State[State["Selecting"] = 2] = "Selecting";
})(State = exports.State || (exports.State = {}));
/**
 * The Launch Dialog prompts the user to log in, and connect to Interactive
 * for them. It calls back with connection details, or undefined if the dialog
 * was dismissed beforehand.
 */
let LinkDialogComponent = class LinkDialogComponent {
    constructor(http, dialogRef, snackRef) {
        this.http = http;
        this.dialogRef = dialogRef;
        this.snackRef = snackRef;
        /**
         * Exposed State enum for the template to consume.
         */
        this.State = State; // tslint:disable-line
        /**
         * Curre state of the component.
         */
        this.state = new BehaviorSubject_1.BehaviorSubject(State.LoggingIn);
        /**
         * List of interactive projects the user owns.
         */
        this.projects = new memorizingSubject_1.MemorizingSubject();
        /**
         * Currently expanded project, listing its owned versions.
         */
        this.expandedProject = new BehaviorSubject_1.BehaviorSubject(0);
    }
    onLoggedIn() {
        this.state.next(State.Loading);
        this.loadProjects();
    }
    /**
     * getLastUpdatedAgo returns the "time ago" of the last updated version
     * of the game.
     */
    getLastUpdatedAgo(game) {
        const timestamp = this.getLastUpdatedDate(game);
        if (timestamp === 0) {
            return 'never';
        }
        return this.getTimeAgo(timestamp);
    }
    /**
     * Returns the "time ago" of the given date / timestamp.
     */
    getTimeAgo(date) {
        return moment(date).fromNow();
    }
    /**
     * getLastUpdatedDate returns the most recent updatedAt of a version of
     * the Interactive game, returning 0 if there are no attached versions.
     */
    getLastUpdatedDate(game) {
        const mostRecentUpdate = game.versions
            .map(version => new Date(version.updatedAt))
            .sort((a, b) => a.getTime() - b.getTime())
            .pop();
        return mostRecentUpdate ? mostRecentUpdate.getTime() : 0;
    }
    /**
     * Chooses the version to link, and closes the dialog.
     */
    select(interactiveVersion, game) {
        this.dialogRef.close(Object.assign({}, interactiveVersion, { game }));
    }
    /**
     * Attempts to create a connection to Interactive. Closes the dialog
     * when it successfully does so.
     */
    loadProjects() {
        this.http.get(env_1.apiUrl('interactive-versions')).subscribe(res => {
            const games = res.json();
            games.sort((a, b) => this.getLastUpdatedDate(b) - this.getLastUpdatedDate(a));
            this.projects.next(games);
            this.state.next(State.Selecting);
        }, err => {
            this.snackRef
                .open('An unknown error occurred', 'Report', { duration: 5000 })
                .onAction()
                .subscribe(() => {
                report_issue_1.reportHttpError('Unknown error in version select dialog', err);
            });
            this.dialogRef.close();
        });
    }
};
LinkDialogComponent = __decorate([
    core_1.Component({
        selector: 'link-dialog',
        templateUrl: './link-dialog.component.html',
        styleUrls: ['../dialog.scss', './link-dialog.component.scss'],
        changeDetection: core_1.ChangeDetectionStrategy.OnPush,
    }),
    __metadata("design:paramtypes", [http_1.Http,
        material_1.MatDialogRef,
        material_1.MatSnackBar])
], LinkDialogComponent);
exports.LinkDialogComponent = LinkDialogComponent;
