import { Component, ChangeDetectionStrategy, Input, NgModule } from '@angular/core';
import { HealthCheckService, BaseListComponent, SortOrder, DataService, ModalService, NotificationService, JobState, SharedModule } from '@ishop/admin-ui/core';
import { FormControl } from '@angular/forms';
import { Router, ActivatedRoute, RouterModule } from '@angular/router';
import { timer } from 'rxjs';
import { takeUntil, filter, map } from 'rxjs/operators';
import { marker } from '@biesbjerg/ngx-translate-extract-marker';

class HealthCheckComponent {
    constructor(healthCheckService) {
        this.healthCheckService = healthCheckService;
    }
}
HealthCheckComponent.decorators = [
    { type: Component, args: [{
                selector: 'vdr-health-check',
                template: "<vdr-action-bar>\r\n    <vdr-ab-left>\r\n        <div class=\"system-status-header\" *ngIf=\"healthCheckService.status$ | async as status\">\r\n            <div class=\"status-icon\">\r\n                <clr-icon\r\n                    [attr.shape]=\"status === 'ok' ? 'check-circle' : 'exclamation-circle'\"\r\n                    [ngClass]=\"{ 'is-success': status === 'ok', 'is-danger': status !== 'ok' }\"\r\n                    size=\"48\"\r\n                ></clr-icon>\r\n            </div>\r\n            <div class=\"status-detail\">\r\n                <ng-container *ngIf=\"status === 'ok'; else error\">\r\n                    {{ 'system.health-all-systems-up' | translate }}\r\n                </ng-container>\r\n                <ng-template #error>\r\n                    {{ 'system.health-error' | translate }}\r\n                </ng-template>\r\n                <div class=\"last-checked\">\r\n                    {{ 'system.health-last-checked' | translate }}:\r\n                    {{ healthCheckService.lastCheck$ | async | localeDate: 'mediumTime' }}\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </vdr-ab-left>\r\n    <vdr-ab-right>\r\n        <vdr-action-bar-items locationId=\"system-status\"></vdr-action-bar-items>\r\n        <button class=\"btn btn-secondary\" (click)=\"healthCheckService.refresh()\">\r\n            <clr-icon shape=\"refresh\"></clr-icon> {{ 'system.health-refresh' | translate }}\r\n        </button>\r\n    </vdr-ab-right>\r\n</vdr-action-bar>\r\n\r\n<table class=\"table\">\r\n    <thead>\r\n        <tr>\r\n            <th class=\"left\">\r\n                {{ 'common.name' | translate }}\r\n            </th>\r\n            <th class=\"left\">\r\n                {{ 'system.health-status' | translate }}\r\n            </th>\r\n            <th class=\"left\">\r\n                {{ 'system.health-message' | translate }}\r\n            </th>\r\n        </tr>\r\n    </thead>\r\n    <tbody>\r\n        <tr *ngFor=\"let row of healthCheckService.details$ | async\">\r\n            <td class=\"align-middle left\">{{ row.key }}</td>\r\n            <td class=\"align-middle left\">\r\n                <vdr-chip [colorType]=\"row.result.status === 'up' ? 'success' : 'error'\">\r\n                    <ng-container *ngIf=\"row.result.status === 'up'; else down\">\r\n                        <clr-icon shape=\"check-circle\"></clr-icon>\r\n                        {{ 'system.health-status-up' | translate }}\r\n                    </ng-container>\r\n                    <ng-template #down>\r\n                        <clr-icon shape=\"exclamation-circle\"></clr-icon>\r\n                        {{ 'system.health-status-down' | translate }}\r\n                    </ng-template>\r\n                </vdr-chip>\r\n            </td>\r\n            <td class=\"align-middle left\">{{ row.result.message }}</td>\r\n        </tr>\r\n    </tbody>\r\n</table>\r\n",
                changeDetection: ChangeDetectionStrategy.OnPush,
                styles: [".system-status-header{display:flex;justify-content:space-between;align-items:flex-start}.system-status-header .status-detail{font-weight:700}.system-status-header .last-checked{font-weight:400;color:var(--color-grey-500)}"]
            },] }
];
HealthCheckComponent.ctorParameters = () => [
    { type: HealthCheckService }
];

class JobListComponent extends BaseListComponent {
    constructor(dataService, modalService, notificationService, router, route) {
        super(router, route);
        this.dataService = dataService;
        this.modalService = modalService;
        this.notificationService = notificationService;
        this.liveUpdate = new FormControl(true);
        this.hideSettled = new FormControl(true);
        this.queueFilter = new FormControl('all');
        super.setQueryFn((...args) => this.dataService.settings.getAllJobs(...args), data => data.jobs, (skip, take) => {
            const queueFilter = this.queueFilter.value === 'all' ? null : { queueName: { eq: this.queueFilter.value } };
            const hideSettled = this.hideSettled.value;
            return {
                options: {
                    skip,
                    take,
                    filter: Object.assign(Object.assign({}, queueFilter), (hideSettled ? { isSettled: { eq: false } } : {})),
                    sort: {
                        createdAt: SortOrder.DESC,
                    },
                },
            };
        });
    }
    ngOnInit() {
        super.ngOnInit();
        timer(5000, 2000)
            .pipe(takeUntil(this.destroy$), filter(() => this.liveUpdate.value))
            .subscribe(() => {
            this.refresh();
        });
        this.queues$ = this.dataService.settings
            .getJobQueues()
            .mapStream(res => res.jobQueues)
            .pipe(map(queues => {
            return [{ name: 'all', running: true }, ...queues];
        }));
    }
    hasResult(job) {
        const result = job.result;
        if (result == null) {
            return false;
        }
        if (typeof result === 'object') {
            return Object.keys(result).length > 0;
        }
        return true;
    }
    cancelJob(id) {
        this.dataService.settings.cancelJob(id).subscribe(() => this.refresh());
    }
}
JobListComponent.decorators = [
    { type: Component, args: [{
                selector: 'vdr-job-list',
                template: "<vdr-action-bar>\r\n    <vdr-ab-left>\r\n        <clr-checkbox-container>\r\n            <clr-checkbox-wrapper>\r\n                <input type=\"checkbox\" clrCheckbox [formControl]=\"liveUpdate\" name=\"live-update\"/>\r\n                <label>{{ 'common.live-update' | translate }}</label>\r\n            </clr-checkbox-wrapper>\r\n            <clr-checkbox-wrapper>\r\n                <input\r\n                    type=\"checkbox\"\r\n                    clrCheckbox\r\n                    [formControl]=\"hideSettled\"\r\n                    name=\"hide-settled\"\r\n                    (change)=\"refresh()\"\r\n                />\r\n                <label>{{ 'system.hide-settled-jobs' | translate }}</label>\r\n            </clr-checkbox-wrapper>\r\n        </clr-checkbox-container>\r\n    </vdr-ab-left>\r\n    <vdr-ab-right>\r\n        <ng-select\r\n            [addTag]=\"false\"\r\n            [items]=\"queues$ | async\"\r\n            [hideSelected]=\"true\"\r\n            [multiple]=\"false\"\r\n            [markFirst]=\"false\"\r\n            [clearable]=\"false\"\r\n            [searchable]=\"false\"\r\n            bindValue=\"name\"\r\n            [formControl]=\"queueFilter\"\r\n            (change)=\"refresh()\"\r\n        >\r\n            <ng-template ng-label-tmp ng-option-tmp let-item=\"item\">\r\n                <ng-container *ngIf=\"item.name === 'all'; else others\">\r\n                    {{ 'system.all-job-queues' | translate }}\r\n                </ng-container>\r\n                <ng-template #others>\r\n                    <vdr-chip [colorFrom]=\"item.name\">{{ item.name }}</vdr-chip>\r\n                </ng-template>\r\n            </ng-template>\r\n        </ng-select>\r\n        <vdr-action-bar-items locationId=\"job-list\"></vdr-action-bar-items>\r\n    </vdr-ab-right>\r\n</vdr-action-bar>\r\n\r\n<vdr-data-table\r\n    [items]=\"items$ | async\"\r\n    [itemsPerPage]=\"itemsPerPage$ | async\"\r\n    [totalItems]=\"totalItems$ | async\"\r\n    [currentPage]=\"currentPage$ | async\"\r\n    (pageChange)=\"setPageNumber($event)\"\r\n    (itemsPerPageChange)=\"setItemsPerPage($event)\"\r\n>\r\n    <vdr-dt-column></vdr-dt-column>\r\n    <vdr-dt-column>{{ 'system.job-queue-name' | translate }}</vdr-dt-column>\r\n    <vdr-dt-column>{{ 'common.created-at' | translate }}</vdr-dt-column>\r\n    <vdr-dt-column>{{ 'system.job-state' | translate }}</vdr-dt-column>\r\n    <vdr-dt-column>{{ 'system.job-duration' | translate }}</vdr-dt-column>\r\n    <vdr-dt-column>{{ 'system.job-result' | translate }}</vdr-dt-column>\r\n    <vdr-dt-column></vdr-dt-column>\r\n    <ng-template let-job=\"item\">\r\n        <td class=\"left align-middle\">\r\n            <vdr-entity-info [entity]=\"job\"></vdr-entity-info>\r\n        </td>\r\n        <td class=\"left align-middle\">\r\n            <vdr-dropdown *ngIf=\"job.data\">\r\n                <button\r\n                    class=\"btn btn-link btn-icon\"\r\n                    vdrDropdownTrigger\r\n                    [title]=\"'system.job-data' | translate\"\r\n                >\r\n                    <clr-icon shape=\"details\"></clr-icon>\r\n                </button>\r\n                <vdr-dropdown-menu>\r\n                    <div class=\"result-detail\">\r\n                        <vdr-object-tree [value]=\"job.data\"></vdr-object-tree>\r\n                    </div>\r\n                </vdr-dropdown-menu>\r\n            </vdr-dropdown>\r\n            <vdr-chip [colorFrom]=\"job.queueName\">{{ job.queueName }}</vdr-chip>\r\n        </td>\r\n\r\n        <td class=\"left align-middle\">{{ job.createdAt | timeAgo }}</td>\r\n        <td class=\"left align-middle\">\r\n            <vdr-job-state-label [job]=\"job\"></vdr-job-state-label>\r\n        </td>\r\n        <td class=\"left align-middle\">{{ job.duration | duration }}</td>\r\n        <td class=\"left align-middle\">\r\n            <vdr-dropdown *ngIf=\"hasResult(job)\">\r\n                <button class=\"btn btn-link btn-sm details-button\" vdrDropdownTrigger>\r\n                    <clr-icon shape=\"details\"></clr-icon>\r\n                    {{ 'system.job-result' | translate }}\r\n                </button>\r\n                <vdr-dropdown-menu>\r\n                    <div class=\"result-detail\">\r\n                        <vdr-object-tree [value]=\"job.result\"></vdr-object-tree>\r\n                    </div>\r\n                </vdr-dropdown-menu>\r\n            </vdr-dropdown>\r\n            <vdr-dropdown *ngIf=\"job.error\">\r\n                <button class=\"btn btn-link btn-sm details-button\" vdrDropdownTrigger>\r\n                    <clr-icon shape=\"exclamation-circle\"></clr-icon>\r\n                    {{ 'system.job-error' | translate }}\r\n                </button>\r\n                <vdr-dropdown-menu>\r\n                    <div class=\"result-detail\">\r\n                        {{ job.error }}\r\n                    </div>\r\n                </vdr-dropdown-menu>\r\n            </vdr-dropdown>\r\n        </td>\r\n        <td class=\"right align-middle\">\r\n            <vdr-dropdown *ngIf=\"!job.isSettled && job.state !== 'FAILED'\">\r\n                <button class=\"icon-button\" vdrDropdownTrigger>\r\n                    <clr-icon shape=\"ellipsis-vertical\"></clr-icon>\r\n                </button>\r\n                <vdr-dropdown-menu vdrPosition=\"bottom-right\">\r\n                    <button\r\n                        type=\"button\"\r\n                        class=\"delete-button\"\r\n                        (click)=\"cancelJob(job.id)\"\r\n                        [disabled]=\"!(['DeleteSettings', 'DeleteSystem'] | hasPermission)\"\r\n                        vdrDropdownItem\r\n                    >\r\n                        <clr-icon shape=\"ban\" class=\"is-danger\"></clr-icon>\r\n                        {{ 'common.cancel' | translate }}\r\n                    </button>\r\n                </vdr-dropdown-menu>\r\n            </vdr-dropdown>\r\n        </td>\r\n    </ng-template>\r\n</vdr-data-table>\r\n",
                changeDetection: ChangeDetectionStrategy.OnPush,
                styles: [".result-detail{margin:0 12px}"]
            },] }
];
JobListComponent.ctorParameters = () => [
    { type: DataService },
    { type: ModalService },
    { type: NotificationService },
    { type: Router },
    { type: ActivatedRoute }
];

class JobStateLabelComponent {
    get iconShape() {
        switch (this.job.state) {
            case JobState.COMPLETED:
                return 'check-circle';
            case JobState.FAILED:
                return 'exclamation-circle';
            case JobState.CANCELLED:
                return 'ban';
            case JobState.PENDING:
            case JobState.RETRYING:
                return 'hourglass';
            case JobState.RUNNING:
                return 'sync';
        }
    }
    get colorType() {
        switch (this.job.state) {
            case JobState.COMPLETED:
                return 'success';
            case JobState.FAILED:
            case JobState.CANCELLED:
                return 'error';
            case JobState.PENDING:
            case JobState.RETRYING:
                return '';
            case JobState.RUNNING:
                return 'warning';
        }
    }
}
JobStateLabelComponent.decorators = [
    { type: Component, args: [{
                selector: 'vdr-job-state-label',
                template: "<vdr-chip [colorType]=\"colorType\">\r\n    <clr-icon [attr.shape]=\"iconShape\"></clr-icon>\r\n    {{ job.state | titlecase }}\r\n    <span *ngIf=\"job.state === 'RUNNING'\" class=\"progress\">\r\n        {{ (job.progress / 100) | percent }}\r\n    </span>\r\n</vdr-chip>\r\n",
                changeDetection: ChangeDetectionStrategy.OnPush,
                styles: [".progress{margin-left:3px}clr-icon{min-width:12px}"]
            },] }
];
JobStateLabelComponent.propDecorators = {
    job: [{ type: Input }]
};

const ɵ0 = {
    breadcrumb: marker('breadcrumb.job-queue'),
}, ɵ1 = {
    breadcrumb: marker('breadcrumb.system-status'),
};
const systemRoutes = [
    {
        path: 'jobs',
        component: JobListComponent,
        data: ɵ0,
    },
    {
        path: 'system-status',
        component: HealthCheckComponent,
        data: ɵ1,
    },
];

class SystemModule {
}
SystemModule.decorators = [
    { type: NgModule, args: [{
                declarations: [HealthCheckComponent, JobListComponent, JobStateLabelComponent],
                imports: [SharedModule, RouterModule.forChild(systemRoutes)],
            },] }
];

// This file was generated by the build-public-api.ts script

/**
 * Generated bundle index. Do not edit.
 */

export { HealthCheckComponent, JobListComponent, JobStateLabelComponent, SystemModule, systemRoutes, ɵ0, ɵ1 };
//# sourceMappingURL=ishop-admin-ui-system.js.map
