import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';

import { ApplicationConfigService } from 'app/core/config/application-config.service';
import { ResilientService, DateTypeEnum } from 'app/resilient/resilient-base/resilient-base.service';
import { IInputDataUpload, NewInputDataUpload } from '../input-data-upload.model';
import { UploadStatus } from 'app/entities/enumerations/upload-status.model';
import { AccountService } from 'app/core/auth/account.service';
import { Resources } from 'app/security/resources.model';
import { SecurityAction } from 'app/security/security-action.model';
import { SecurityPermission } from 'app/security/security-permission.model';

export type EntityResponseType = HttpResponse<IInputDataUpload>;
export type EntityArrayResponseType = HttpResponse<IInputDataUpload[]>;

@Injectable({ providedIn: 'root' })
export class InputDataUploadService extends ResilientService<IInputDataUpload, NewInputDataUpload> {
  protected http = inject(HttpClient);
  protected applicationConfigService = inject(ApplicationConfigService);

  private accountService = inject(AccountService);

  /* ResilientService - Overriden methods */
  /* ************************************ */
  override canUpdate(inputDataUpload: IInputDataUpload): boolean {
    // Check InputDataUpload State
    if (inputDataUpload && inputDataUpload.state !== UploadStatus.UPLOADED) {
      return false;
    }

    // Check if the Period is still OPEN to allow changes
    // TODO

    // Check if user permission is SecurityPermission.HIERARCHY.
    // In this case, must check if user has access to inputDataUpload.owner
    const securityPermission: SecurityPermission = this.accountService.getPermission(Resources.INPUT_DATA_UPLOAD, SecurityAction.UPDATE);
    if (SecurityPermission.HIERARCHY === securityPermission) {
      if (this.accountService.getParentOrganization()?.id != inputDataUpload.owner?.id) {
        return false;
      }
    }

    return true;
  }
  


  /* ResilientService - Service Methods */
  /* ********************************** */
  private readonly resourceUrl = this.applicationConfigService.getEndpointFor('api/input-data-uploads');
  override getResourceUrl(): string { return this.resourceUrl; }
  
  private readonly dateProperties: Map<string, string> = new Map([
      ["creationDate", DateTypeEnum.TIMESTAMP]
  ]);
  override getDateProperties(): Map<string, string> { return this.dateProperties; }
  
  
  doLoad(id: number): Observable<HttpResponse<{}>> {
    return this.http.get(`${this.resourceUrl}/${id}/doLoad`, { observe: 'response' });
  }
  

}
