import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";
import {map} from "rxjs";
import {Picture} from "./Picture";

@Injectable({
  providedIn: 'root'
})
export class PictureService {

  readonly secure = location.protocol.endsWith('s:') ? 's' : '';

  constructor(
    readonly http: HttpClient,
  ) {
    //
  }

  all(next: (list: Picture[]) => any): void {
    this.http.get<any[]>(this.apiUrl("http", ['Picture', 'all'])).pipe(map(list => list.map(Picture.fromJson))).subscribe(next);
  }

  upload(file: File, success: () => any, error: () => any): void {
    const form = new FormData();
    form.append('file', file);
    this.http.post(this.apiUrl("http", ['Picture', 'upload']), form).subscribe({next: success, error: error});
  }

  apiUrl(protocol: string, path: string[]): string {
    return `${protocol}${this.secure}://${location.hostname}/api/${path.join('/')}`;
  }

}
