import {Component, ElementRef, Inject, Input, OnInit, ViewChild} from '@angular/core'; import {ApiService, ResourceNotAvailableOfflineError} from '../../../service/api.service'; import { APP_BASE_HREF } from '@angular/common'; import {EditorService} from '../../../service/editor.service'; import {EditorNodeContract} from '../../nodes/EditorNode.contract'; @Component({ selector: 'editor-files', templateUrl: './files.component.html', styleUrls: ['./files.component.scss'], }) export class FilesComponent extends EditorNodeContract implements OnInit { @Input() nodeId: string; @Input() editorUUID: string; @ViewChild('uploadForm') uploadForm: ElementRef; public fileRecords: Array = []; public pendingSetup = true; public dbRecord: any = {}; public dirty = false; public notAvailableOffline = false; public get readonly() { return !this.node || !this.editorService.canEdit(); } constructor( protected api: ApiService, public editorService: EditorService, @Inject(APP_BASE_HREF) private baseHref: string ) { super(); } public isDirty(): boolean | Promise { return this.dirty; } public writeChangesToNode(): void | Promise { this.node.Value.Mode = 'files'; } public needsLoad(): boolean | Promise { return this.node && this.pendingSetup; } public async performLoad(): Promise { if ( !this.node.Value ) { this.node.Value = {}; } if ( !this.node.Value.Value && !this.readonly ) { this.dbRecord = await this.api.createFileGroup(this.page.UUID, this.node.UUID); this.fileRecords = this.dbRecord.files; this.node.Value.Mode = 'files'; this.node.Value.Value = this.dbRecord.UUID; this.node.value = this.dbRecord.UUID; this.dirty = true; } else { try { this.dbRecord = await this.api.getFileGroup(this.page.UUID, this.node.UUID, this.node.Value.Value); this.fileRecords = this.dbRecord.files; this.notAvailableOffline = false; } catch (e) { if ( e instanceof ResourceNotAvailableOfflineError ) { this.notAvailableOffline = true; } else { throw e; } } } this.pendingSetup = false; } public async performDelete(): Promise { await this.api.deleteFileGroup(this.page.UUID, this.node.UUID, this.node.Value.Value); } ngOnInit() { this.editorService = this.editorService.getEditor(this.editorUUID); this.editorService.registerNodeEditor(this.nodeId, this).then(() => { }); } getApiSubmit() { return this.api._build_url(`files/upload/${this.page.UUID}/${this.node.UUID}/${this.node.Value.Value}`); } onSubmitClick() { if ( this.readonly ) { return; } this.uploadForm.nativeElement.submit(); } getReturnUrl() { return `${this.baseHref}editor;id=${this.page.UUID}`; } downloadFile(fileRecord) { // tslint:disable-next-line:max-line-length window.open(this.api._build_url(`files/${this.page.UUID}/${this.node.UUID}/get/${this.node.Value.Value}/${fileRecord._id}`), '_blank'); } }