import { Injectable, EventEmitter } from '@angular/core';
import { environment } from '../environments/environment';
import { HttpClient, HttpHeaders, HttpParams, HttpRequest, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs/internal/Observable';
import swal from 'sweetalert2';

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

  public loader: EventEmitter<any> = new EventEmitter();

  constructor(private http: HttpClient) {

  }

    private getAuthToken() {
      return localStorage.getItem('GreenappToken');
    }
    public get(url:string, body?:any) {
      return  this.http.get(environment.apiUrl+url, {
        params: body,
        headers: new HttpHeaders().append('Authorization', this.getAuthToken())
      });
    }
    public post(url:string, body?:any) {
      return  this.http.post(environment.apiUrl+url, body,{
        headers: new HttpHeaders().append('Authorization', this.getAuthToken())
      });
    }
    public postNotAuth(url:string, body?:any) {
      return  this.http.post(environment.apiUrl+url, body,{
        headers: new HttpHeaders().append('Authorization', this.getAuthToken())
      });
    }
    public login(rut: string, clave: string) {
      return this.http.post(environment.apiUrl+'users/login', { rut: rut, password: clave, level: 10 });
    }
    public upload(url: string, file: File) {

      let formData = new FormData();
      formData.append('upload', file);
  
      let params = new HttpParams();
      const options = {
        headers: new HttpHeaders().append('Authorization', this.getAuthToken())
      };
  
      //const req = new HttpRequest('POST', environment.apiUrl+url, formData, options);
      return this.http.post(environment.apiUrl+url, formData, options);
    }
    public showError(msg: string, text?: string) {
      swal({
        //position: 'top-end',
        type: 'error',
        title: msg,
        text: (text ? text : null),
        showConfirmButton: false,
        showCancelButton: true,
        cancelButtonText: 'Aceptar',
        focusCancel: true
        //timer: 1500
      });
    }
    public showOk(msg: string, text?: string) {
      swal({
        //position: 'top-end',
        type: 'success',
        title: msg,
        text: (text ? text : null),
        showConfirmButton: false,
        showCancelButton: true,
        cancelButtonText: 'Aceptar',
        focusCancel: true
        //timer: 1500
      });
    }
    public confirm(msg: string, text?: string) {
      return swal({
        type: 'question',
        title: msg,
        text: (text ? text : null),
        showConfirmButton: true,
        showCancelButton: true,
        cancelButtonText: 'Cancelar',
        confirmButtonText: 'Aceptar',
        focusCancel: true
      });
    }
    public prompt(title: string) {
      return swal({
        title: title,
        input: 'text',
        inputAttributes: {
          autocapitalize: 'off'
        },
        showCancelButton: true,
        cancelButtonText: 'Cancelar',
        confirmButtonText: 'Aceptar',
        showLoaderOnConfirm: true,
        allowOutsideClick: () => swal.isLoading()
      });
    }
    /* Common */
    public getStates() {
      return this.get("states");
    }
    public getCities(state:string) {
      return this.get("cities/"+state);
    }
    public saveUser(data:any) {
      return this.post("erp/user/save", data);
    }
    public getTerms() {
      return this.get("terms");
    }
    public sendToApp(data:any) {
      return this.post("terms/update", data);
    }
    /* Customers */
    public saveCustomer(data:any) {
      return this.post("erp/customers/save", data);
    }
    public getCustomerInvitations() {
      return this.get("erp/customers/invitations");
    }
    public saveInvitation(data: any) {
      return this.post("erp/customers/invitations/save", data);
    }
    public deleteInvitation(id: string) {
      return this.post("erp/customers/invitations/delete", {id: id});
    }
    public getCustomers(name: string, state: string) {
      return this.get("erp/users", { name: name, state: state, groups: 1 })
    }
    public getCustomerPrescriptions(id: string) {
      return this.get("erp/users/"+id+"/prescriptions");
    }
    public getCustomerBalance(id: string) {
      return this.get("erp/users/"+id+"/balance");
    }
    public deleteUser(id:string) {
      return this.post("erp/user/delete", {id:id});
    }
    /* Pending Prescriptions */
    public getPendingPrescriptions() {
      return this.get("erp/prescriptions/pending");
    }
    public authorizePrescription(id:string) {
      return this.post("erp/prescriptions/auth",{ id: id});
    }
    public rejectPrescription(id:string, reason:string) {
      return this.post("erp/prescriptions/noauth", {id: id, reason: reason});
    }
    /* Orders */
    public getOrders(name:string,from:string,to:string,delivery_from:string,delivery_to:string) {
      return this.get("erp/orders", {name:name,from:from,to:to,delivery_from:delivery_from,delivery_to:delivery_to});
    }
    public nullOrder(id:string) {
      return this.post("erp/orders/delete", {id:id});
    }
    public saveOrder(data:any) {
      return this.post("erp/orders/save", data);
    }
    public getPacking(id:string) {
      return this.get("erp/orders/"+id+"/packing");
    }
    public processOrder(id:string) {
      return this.post("erp/orders/process", {id:id});
    }
    /* Users */
    public getUsers() {
      return this.get("erp/users", { name: '', state: '', groups: 10 })
    }
    public getDeliveryman() {
      return this.get("erp/users", { name: '', state: '', groups: 5 })
    }
    public uploadImage(file: File) {
      return this.upload('erp/upload', file);
    }
    /* products */
    public getProducts(name:string,type:string) {
      return this.get("erp/products", { name: name, type: type })
    }
    public deleteProduct(id:string) {
      return this.post("erp/products/delete", {id:id});
    }
    public saveProduct(data:any) {
      return this.post("erp/products/save", data);
    }
    public getCategories() {
      return this.get("erp/categories")
    }
    public deleteCategory(id:string) {
      return this.post("erp/categories/delete", {id:id});
    }
    public saveCategory(data:any) {
      return this.post("erp/categories/save", data);
    }
    public getWarehouses() {
      return this.get("erp/warehouse")
    }
    public deleteWarehouse(id:string) {
      return this.post("erp/warehouse/delete", {id:id});
    }
    public saveWarehouse(data:any) {
      return this.post("erp/warehouse/save", data);
    }
    /* Report */
    public excelKardex(from:string,to:string) {
      return this.get("erp/reports/kardex", {from:from,to:to});
    }
    public excelAccounts(from:string,to:string) {
      return this.get("erp/reports/accounts", {from:from,to:to});
    }
    /* Notifications */
    public sendPush(data: any) {
      return this.post("erp/notification/send", data);
    }
    /* Dashboard */
    public getStats() {
      return this.get("erp/stats");
    }
}
