import { Injectable} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../../../environments/environment';

import { SaleInfo } from '../model/saleInfo.interface';
import { Sale } from '../model/sale.interface';

@Injectable({
    providedIn: 'root'
})
export class apiSaleService {
    ServeurURL = environment.ServeurURL;
    ApiURL = this.ServeurURL+"/api";

    constructor(
        private http: HttpClient){}    

    // Sale
    getSaleInfos(url: string): Observable<SaleInfo> {
        let encodeUrl = encodeURIComponent(url);

        return this.http.get<SaleInfo>(this.ApiURL+'/sale/getSaleInfos/'+encodeUrl);
    }

    prepareSale(Sale: Sale): Observable<any> {
        
        let follow = this.http.get<any>(this.ApiURL+'/sale/prepareSale/'+Sale._id);
        return follow
    }

    followSale(Sale: Sale): Observable<any> {
        
        let follow = this.http.get<any>(this.ApiURL+'/sale/followSale/'+Sale._id);
        return follow
    }

    resetSaleToReady(_id: String): void {
        this.getSale(_id).subscribe((sale: Sale) => {
            sale.status = "ready";
            this.updateSale(sale).subscribe();
        });
    }

    // Sale CRUD  

    getSale(_id: String): Observable<Sale> {
        return this.http.get<Sale>(this.ApiURL+'/sale/sale/'+_id);
    }

    saveSale(Sale: Sale): Observable<Sale> {
        return this.http.post<Sale>(this.ApiURL+'/sale/sale', Sale);
    }

    updateSale(Sale: Sale): Observable<Sale> {
        return this.http.put<Sale>(this.ApiURL+'/sale/sale/'+Sale._id, Sale);
    }

    deleteSale(_id: String): Observable<any> {
        return this.http.delete<any>(this.ApiURL+'/sale/sale/'+_id);
    }

    // Function DB Sale    

    getAllSale(): Observable<SaleInfo[]> {
        return this.http.get<SaleInfo[]>(`${this.ApiURL}/sale/getAll`);
    }

    postProcessing(_id: String): Observable<any> {
        return this.http.get<any>(this.ApiURL+'/sale/postProcessing/'+_id);
    }

    getSaleStatXsl(_id: String): Observable<any> {
        return this.http.get<Blob>(this.ApiURL+'/sale/SaleStatXsl/'+_id, { responseType: 'blob' as 'json' });
    }
    
}
