import {
  HttpRequest,
  HttpClient,
  HttpEvent,
  HttpEventType,
} from "@angular/common/http";
import { catchError, map } from "rxjs/operators";
import { Observable, of } from "rxjs";
import {
  FilePickerAdapter,
  UploadResponse,
  UploadStatus,
  FilePreviewModel,
} from "ngx-awesome-uploader";

export class Adapter extends FilePickerAdapter {
  constructor(private http: HttpClient) {
    super();
  }
  public uploadFile(fileItem: FilePreviewModel): Observable<UploadResponse> {
    const form = new FormData();
    form.append("file", fileItem.file);
    form.append("category", "image");
    form.append("folder", "image");
    const api = "https://api-roadreport.pisdev.my.id/api/upload-dumps";
    const req = new HttpRequest("POST", api, form, { reportProgress: true });
    return this.http.request(req).pipe(
      map((res: HttpEvent<any>) => {
        if (res.type === HttpEventType.Response) {
          const responseFromBackend = res.body;
          return {
            body: responseFromBackend,
            status: UploadStatus.UPLOADED,
          };
        } else if (res.type === HttpEventType.UploadProgress) {
          if (res.total !== undefined) {
            const uploadProgress = +Math.round((100 * res.loaded) / res.total);
            return {
              status: UploadStatus.IN_PROGRESS,
              progress: uploadProgress,
            };
          }
        }
        return {
          status: UploadStatus.ERROR,
          body: undefined,
        };
      }),
      catchError((er) => {
        return of({ status: UploadStatus.ERROR, body: er });
      })
    );
  }
  public removeFile(): Observable<any> {
    const removeApi = "https://api-roadreport.pisdev.my.id/api/upload-dumps";
    return this.http.post(removeApi, {});
  }
}
