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

import { DropZoneResp, DropZoneReq } from "../models/dropzone";

import { BaseService } from "./base.service";
import { RefData } from "../models/ref-data.enum";

@Injectable()
export class DropzoneService extends BaseService {
  constructor(private http: HttpClient) {
    super();
  }

  public getListOfDropZones(simple: boolean = false): Observable<Array<DropZoneResp>> {
    let url : string;
    if (simple === true) {
      url = `${this.apiUrl}/DropZone/GetSimple`;
    } else {
      url = `${this.apiUrl}/DropZone`;
    }

    let callToApi =  this.http.get<Array<DropZoneResp>>(url, { headers: this.headers })
                              .pipe(map(response => {
                                const details = response.map(data => new DropZoneResp(data));
                                return details;
                              }));
    return this.serviceRefData.get<Array<DropZoneResp>>(RefData.Dropzone, callToApi);
  }

  public SetFavoriteDropZone(selectedDz: DropZoneResp): boolean {
    selectedDz.isFavorite = true;
    
    this.http.put(`${this.apiUrl}/DropZone/AddToFavorite/${selectedDz.id}`, 
                  selectedDz,
                  { headers: this.headers })
             .subscribe();

    return true;
  }

  public RemoveFavoriteDropZone(selectedDz: DropZoneResp): boolean {
    selectedDz.isFavorite = false;
    
    this.http.put(`${this.apiUrl}/DropZone/RemoveToFavorite${selectedDz.id}`, 
                  selectedDz, 
                  { headers: this.headers })
              .subscribe();

    return true;
  }

  public AddDropZone(latitude: string,
                     longitude: string,
                     name: string,
                     address: string,
                     website: string,
                     email: string,
                     type: Array<string>,
                     isFavorite: boolean) {
    const bodyNewDropZone: DropZoneReq = {
      id: 0,
      latitude: latitude,
      longitude: longitude,
      name: name,
      address: address,
      website: website,
      email: email,
      type: type,
      isFavorite: isFavorite
    };

    return this.http.post(`${this.apiUrl}/DropZone`,
                          bodyNewDropZone, 
                          { headers: this.headers });
  }
}
