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

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

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

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

  all(next: (list: Picture[]) => any): void {
    this.http.post<any[]>(this.apiUrl("http", ['Picture', 'all']), this.adminService.password).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});
  }

  toggleVisible(picture: Picture, next: (list: Picture[]) => any) {
    if (!this.adminService.password) {
      throw new Error("You are not logged in.");
    }
    this.http.post<any[]>(this.apiUrl("http", ['Picture', picture.uuid, 'visible', !picture.visible]), this.adminService.password).pipe(map(list => list.map(Picture.fromJson))).subscribe(next);
  }

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

}
