import * as React from "react";
import { injectable, postConstruct, inject } from "inversify";
import { ReactWidget } from "@theia/core/lib/browser/widgets/react-widget";
import {
  FileDialogService,
  OpenFileDialogProps,
} from "@theia/filesystem/lib/browser";
import { WorkspaceService } from "@theia/workspace/lib/browser/workspace-service";
import { MessageService } from "@theia/core";
import StorjWidget from "./components/StorjWidget";
import { StorjWidgetProvider } from "./components/StorjWidget/StorjWidget.context";
import { StorjWidgetBackendService } from "../common/protocol";

@injectable()
export class GalileoIdeStorjWidgetWidget extends ReactWidget {
  static readonly ID = "galileo-ide-storj-widget:widget";
  static readonly LABEL = "Access Storj";

  @inject(MessageService)
  protected readonly messageService!: MessageService;

  @inject(FileDialogService)
  protected readonly fileDialogService!: FileDialogService;

  @inject(WorkspaceService)
  protected readonly workspaceService!: WorkspaceService;

  @inject(StorjWidgetBackendService)
  protected readonly storjWidgetService!: StorjWidgetBackendService;

  @postConstruct()
  protected async init(): Promise<void> {
    this.id = GalileoIdeStorjWidgetWidget.ID;
    this.title.label = GalileoIdeStorjWidgetWidget.LABEL;
    this.title.caption = GalileoIdeStorjWidgetWidget.LABEL;
    this.title.closable = true;
    this.title.iconClass = "galileo-storj-logo";
    this.update();
  }

  protected async handleShowFileDialog(options: OpenFileDialogProps) {
    const root = this.workspaceService.tryGetRoots()[0];
    return this.fileDialogService.showOpenDialog(options, root);
  }

  protected async handleShowAlert(message: string) {
    return this.messageService.info(message);
  }

  protected getIsPathFile(path: string) {
    return this.storjWidgetService.getIsPathFile(path);
  }

  protected render(): React.ReactNode {
    return (
      <StorjWidgetProvider>
        <StorjWidget
          onShowFileDialog={(options: OpenFileDialogProps) =>
            this.handleShowFileDialog(options)
          }
          onShowAlert={(message: string) => this.handleShowAlert(message)}
          getIsPathFile={(path: string) => this.getIsPathFile(path)}
        />
        <div className="watermark-container">
          <div className="hypernet-watermark"></div>
        </div>
      </StorjWidgetProvider>
    );
  }
}
