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 interface ReportSurvey {
  abs_path: string;
}

export class AdaperSurveyor extends FilePickerAdapter {
  imageFiles: ReportSurvey = { abs_path: "" };

  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;
          this.imageFiles = {
            abs_path: responseFromBackend.data.abs_path,
          };

          console.log(responseFromBackend);

          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: "Unknown error occurred during upload process.",
        };
      }),
      catchError((er) => {
        return of({ status: UploadStatus.ERROR, body: er });
      })
    );
  }

  public removeFile(fileItem: FilePreviewModel): Observable<any> {
    const id = 50;
    const removeApi = `https://api-roadreport.pisdev.my.id/api/upload-dumps/${id}`;
    return this.http.post(removeApi, { id });
  }
}
