import Bind from "@web-atoms/core/dist/core/Bind";
import { CancelToken } from "@web-atoms/core/dist/core/types";
import XNode from "@web-atoms/core/dist/core/XNode";
import { Inject } from "@web-atoms/core/dist/di/Inject";
import { NavigationService } from "@web-atoms/core/dist/services/NavigationService";
import { AtomWindowViewModel } from "@web-atoms/core/dist/view-model/AtomWindowViewModel";
import Load from "@web-atoms/core/dist/view-model/Load";
import { AtomWindow } from "@web-atoms/core/dist/web/controls/AtomWindow";
import FileModel from "../../model/FileModel";
import FileUploadService from "../../services/FileUploadService";

class FileUploaderViewMode extends AtomWindowViewModel {

    public file: FileModel;

    public files: File[];

    public progress: number = 0;

    public error: string = "";

    @Inject
    private navigationService: NavigationService;

    @Inject
    private fileUploadService: FileUploadService;

    private cancelToken: CancelToken;

    @Load({ init: true })
    public async loadFiles() {
        try {
            this.cancelToken = new CancelToken();
            this.registerDisposable({
                dispose: () => this.cancelToken.cancel()
            });
            this.closeWarning = "Are you sure you want to cancel the file upload?";
            const result = await this.fileUploadService.uploadAsync(this.files, (s, t) => {
                this.progress = Math.round((100 * s) / t);
            }, this.cancelToken);
            for (let index = 0; index < this.files.length; index++) {
                const element = this.files[index];
                const url = result[index];
                const file = this.file.get(element.name, true);
                file.tempUrl = url;
                file.remoteUrl = url;
            }
            this.closeWarning = null;
            this.close();
        } catch (e) {
            this.error = e.stack ? e.stack : e.toString();
        }
        this.closeWarning = null;
    }

}

export default class FileUploader extends AtomWindow {

    public viewModel: FileUploaderViewMode;

    public create() {

        this.viewModel = this.resolve(FileUploaderViewMode);

        this.render(<AtomWindow>
            <AtomWindow.windowTemplate>
                <div>
                    <span text={Bind.oneWay(() => !this.viewModel.error
                        ? `Uploading ... ${this.viewModel.progress}%`
                        : `Upload Failed with error ${this.viewModel.error}`)}/>
                </div>
            </AtomWindow.windowTemplate>
            <AtomWindow.commandTemplate>
                <button
                    eventClick={Bind.event(() => this.viewModel.cancel())}>Cancel</button>
            </AtomWindow.commandTemplate>
        </AtomWindow>);
    }

}
