import {NotNull, ObjectRef} from "@webbpm/base-package";
import {ChangeDetectionStrategy, Component} from "@angular/core";
import {FileItem} from "ng2-file-upload";
import {EmployeeInfoFileFormType} from "./EmployeeInfoFileFormType";
import {TokenConstants} from "../../../modules/security/TokenConstants";
import {ErvuFileUpload} from "./ErvuFileUpload";
import {FileLikeObject} from "ng2-file-upload/file-upload/file-like-object.class";

@Component({
             moduleId: module.id,
             selector: "ervu-additional-file-upload",
             templateUrl: "./../../../../../src/resources/template/ervu/component/ErvuFileUpload.html",
             changeDetection: ChangeDetectionStrategy.OnPush
           })
export class ErvuFileUploadWithAdditionalFiles extends ErvuFileUpload {

  @ObjectRef()
  @NotNull()
  public signFileUploadRef: ErvuFileUpload;
  @ObjectRef()
  @NotNull()
  public mchdFileUploadRef: ErvuFileUpload;

  public setUploaderMethods() {
    this.uploader.onBeforeUploadItem = (fileItem: FileItem) => {
      const additionalParams: any = {
        signFile: this.signFileUploadRef.uploader.queue[0]._file
      };

      if (this.mchdFileUploadRef && this.mchdFileUploadRef.uploader.queue.length > 0) {
        additionalParams.mchdFile = this.mchdFileUploadRef.uploader.queue[0]._file;
      }

      //refresh headers
      this.uploader.setOptions({
                                 headers: [
                                   {
                                     name: "X-Employee-Info-File-Form-Type",
                                     value: EmployeeInfoFileFormType[this.formType]
                                   },
                                   {
                                     name: "Client-Time-Zone",
                                     value: Intl.DateTimeFormat().resolvedOptions().timeZone
                                   },
                                   {
                                     name: TokenConstants.CSRF_HEADER_NAME,
                                     value: this.cookieService.get(TokenConstants.CSRF_TOKEN_NAME)
                                   }
                                 ],
                                 additionalParameter: additionalParams
                               });
      this.fileUploadStartEvent.trigger();
      this.isDropZoneVisible = false;
      this.isFilesListVisible = false;
      this.isProgressBarVisible = true;
      this.cd.markForCheck();
    };
    this.uploader.onErrorItem = (item: FileItem,
                                 response: string) => {
      this.fileUploadFailedEvent.trigger();
      this.uploader.cancelAll();
      try {
        var error = JSON.parse(response);
        error.messages.forEach((errorMessage) => {
          this.messagesService.error(errorMessage, error);
        })
      }
      catch (error) {
        this.messagesService.error(`Не удалось отправить следующие файлы: ${item.file.name}`
                                   + ` ${this.uploader.getNotUploadedItems()
                .map(notUploadeditem => notUploadeditem.file.name)
                .join(', ')}.`);
      }
      this.fileInputEl.value = null;
      this.uploader.clearQueue();
      this.mchdFileUploadRef.uploader.clearQueue();
      this.mchdFileUploadRef.fileInputEl.value = null;
      this.signFileUploadRef.uploader.clearQueue();
      this.signFileUploadRef.fileInputEl.value = null;
      this.isDropZoneVisible = true;
      this.isFilesListVisible = true;
      this.isProgressBarVisible = false;
      this.isUploadErrorOccurred = true;
      this.cd.markForCheck();
    };

    this.uploader.onCompleteAll = () => {
      if (!this.isUploadErrorOccurred) {
        this.uploader.clearQueue();
        this.mchdFileUploadRef.uploader.clearQueue();
        this.signFileUploadRef.uploader.clearQueue();
        this.fileInputEl.value = null;
        this.mchdFileUploadRef.fileInputEl.value = null;
        this.signFileUploadRef.fileInputEl.value = null;
        this.fileUploadEndEvent.trigger();
        this.isProgressBarVisible = false;
        this.cd.markForCheck();
      }
    };

    this.uploader.onAfterAddingFile = (fileItem: FileItem) => {
      this.fileAddedEvent.trigger();
    }

    this.uploader.onWhenAddingFileFailed = (item: FileLikeObject, filter: any, options: any) => {
      switch (filter.name) {
        case "fileSize":
          this.messagesService.error(`Размер файла ${item.name} превышает предельно допустимый = ${this.maxFileSizeMb} MB`);
          break;
        case "queueLimit":
          this.messagesService.error(`Не удалось добавить файл ${item.name}. `
                                     + `Достигнуто максимальное количество файлов для загрузки = ${this.maxFilesToUpload}`);
          break;
        case "extension":
          this.messagesService.error(`Файл ${item.name} имеет недопустимое расширение.`);
          break;
        default:
          this.messagesService.error(`Не удалось добавить файл ${item.name}.`);
      }
      this.fileInputEl.value = null;
      this.cd.markForCheck();
    };
  }
}
