import { Injectable, Inject } from '@angular/core';

import { FileUtil } from '@ucap/core';
import { I18nService, UCAP_I18N_NAMESPACE } from '@ucap/ng-i18n';
import { CommonApiService } from '@ucap/ng-api-common';
import { Store } from '@ngrx/store';

@Injectable({
  providedIn: 'root'
})
export class AppFileService {
  constructor(
    private store: Store<any>,
    private i18nService: I18nService,
    private commonApiService: CommonApiService
  ) {
    this.i18nService.setDefaultNamespace('common');
  }

  async validUploadFile(
    fileList: FileList,
    fileAllowSize: number = 50
  ): Promise<boolean> {
    let valid = true;

    // File size check.
    // tslint:disable-next-line: prefer-for-of
    for (let i = 0; i < fileList.length; i++) {
      const file = fileList[i];
      if (file.size > fileAllowSize * 1024 * 1024) {
        const msg = this.i18nService.t('common.file.errors.oversize', {
          maxSize: fileAllowSize
        });
        alert(msg);

        valid = false;
        return valid;
      }
    }

    // Extention check.
    const checkExt = this.commonApiService.acceptableExtensionForFileTalk(
      FileUtil.getExtensions(fileList)
    );
    if (!!checkExt) {
      const msg = this.i18nService.t('common.file.errors.notSupporedType', {
        supporedType: checkExt.join(',')
      });
      alert(msg);
      // this.snackBarService.openFromComponent<
      //   AlertSnackbarComponent,
      //   AlertSnackbarData
      // >(AlertSnackbarComponent, {
      //   duration: 1000,
      //   verticalPosition: 'bottom',
      //   horizontalPosition: 'center',
      //   data: {
      //     html: this.translateService.instant(
      //       'common.file.errors.notSupporedType',
      //       {
      //         supporedType: checkExt.join(',')
      //       }
      //     )
      //   }
      // });
      valid = false;
      return valid;
    }

    // Fake media file check.
    const fakeMedia = await this.commonApiService.checkInvalidMediaMimeForFileTalkForFileList(
      fileList
    );
    if (!!fakeMedia) {
      const msg = this.i18nService.t('common.file.errors.notAcceptableMime', {
        supporedType: fakeMedia.join(',')
      });
      alert(msg);

      valid = false;
      return valid;
    }

    return valid;
  }
}
