import { CookieService } from 'ngx-cookie-service';
import { environment } from './../../../environments/environment.prod';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class BaseService {
	public ids: string[] = [];
  
  constructor(
    private httpClient: HttpClient,
    private cookieService: CookieService,
    public router: Router
  ) { }

  getnodeHeaders(){
    var nodeheaders= new HttpHeaders()
       
    .set('Content-Type', 'application/x-www-form-urlencoded');
    return nodeheaders;
   }

  getHeaders() {
    let headers;
    let token = this.cookieService.get('token')
    // if (this.cookieService.get('token')) {
    if (token) {

      headers = new HttpHeaders()
        .set('Authorization', 'Bearer ' + token)

         //.set('Access-Control-Allow-Origin', '*')
        //.set('Authorization', 'Basic YWRtaW46cmF5NyNJbmZpeGVk') // admin ray7#Infixed
        // .set('Authorization', 'Basic c3VqYXRhOlN1amF0YTEyMzQ=') //sujata
        .set('Content-Type', 'application/x-www-form-urlencoded');
    } else {
      headers = new HttpHeaders()
        // .set('Authorization', 'Bearer ' + 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJwcmFzaGFudGoiLCJleHAiOjE3MjA2MzI1MDQsImlhdCI6MTcyMDYyNTMwNCwiaGFuZGxlIjoicHJhc2hhbnRqIn0.tcevwNjehU1OLGnGGQLpFW7MNGinOmCtidIy4Z2msycC0CRCleB1FZmcKtDAzFgoU7nLmM1_uusEGrinlTHF7w')
        .set('Content-Type', 'application/x-www-form-urlencoded');
    }
    return headers ;
  }

  // getJSONHeaders() {
  //   let headers;
  //   if (this.cookieService.get('token')) {
  //     headers = new HttpHeaders()
  //       .set('Authorization', 'Bearer ' + this.cookieService.get('token'))
  //        //.set('Access-Control-Allow-Origin', '*')
  //       //.set('Authorization', 'Basic YWRtaW46cmF5NyNJbmZpeGVk') // admin ray7#Infixed
  //       // .set('Authorization', 'Basic c3VqYXRhOlN1amF0YTEyMzQ=') //sujata
  //       .set('Content-Type', 'application/json');
  //   } else {
  //     headers = new HttpHeaders()
  //       .set('Content-Type', 'application/json');
  //   }
  //   return headers ;
  // }

  getJSONHeaders(): HttpHeaders {
    let headers;
    if (this.cookieService.get('token')) {
      headers = new HttpHeaders()
        .set('Authorization', 'Bearer ' + this.cookieService.get('token'))
        .set('Content-Type', 'application/json');
    } else {
      headers = new HttpHeaders()
        .set('Content-Type', 'application/json');
    }
    return headers;
  }
getData(url: string, params?: any) {

  let options: any = {
    headers: this.getHeaders()
  };

  if (params) {
    let httpParams = new HttpParams();

    Object.keys(params).forEach(key => {
      if (params[key] !== null && params[key] !== undefined && params[key] !== '') {
        httpParams = httpParams.set(key, params[key]);
      }
    });

    options.params = httpParams;
  }

  return this.httpClient.get(`${environment.backendHost}${url}`, options);
}


  // getData(url: string) {
  //   return this.httpClient.get(`${environment.backendHost}${url}`, { headers: this.getHeaders() });
  // }

  postData(url: string, payload: any) {
    return this.httpClient.post(`${environment.backendHost}${url}`, payload, { headers: this.getHeaders() });
  }

  postData1(url: string) {
    return this.httpClient.post(`${environment.backendHost}${url}`,"",{ headers: this.getHeaders() });
  }

  deleteData(url: string) {
    return this.httpClient.delete(`${environment.backendHost}${url}`, { headers: this.getHeaders() });
  }

  putData(url: string, payload: any) {
    return this.httpClient.put(`${environment.backendHost}${url}`, payload, { headers: this.getHeaders() });
  }

  // putJSONData(url: string, payload: any) {
  //   return this.httpClient.put(`${environment.backendHost}${url}`, payload, { headers: this.getJSONHeaders() });
  // }

  putJSONData(url: string, payload: any): Observable<any> {
    return this.httpClient.put(`${environment.backendHost}${url}`, payload, { headers: this.getJSONHeaders() });
  }

  getUserName(url:string){
    return this.httpClient.get(`${environment.backendHost}${url}`,{headers: this.getnodeHeaders()});
  }
  postDataNodeFramwork(url: string, payload: any) {
    return this.httpClient.post(`${environment.backendHost}${url}`, payload, { headers: this.getnodeHeaders() });
  }
  getDataNodeFramwork(url: string) {
    return this.httpClient.get(`${environment.backendHost}${url}`,{ headers: this.getnodeHeaders() });
  }
  putDataNodeFramwork(url: string, payload: any) {
    return this.httpClient.put(`${environment.backendHost}${url}`, payload, { headers: this.getnodeHeaders() });
  }
  getDevicepermissionlist(url: string ,payload:any){
    return this.httpClient.post(`${environment.backendHost}${url}`,payload,{headers: this.getnodeHeaders()})
  }
  getDevicesperUser(url: string, payload:any){
    return this.httpClient.post(`${environment.backendHost}${url}`,payload,{headers: this.getnodeHeaders()})
  }
  UserValidatepost(url: string, payload: any) {
    let tre =  this.httpClient.post(`${environment.backendHost}${url}`, payload,{ headers: this.getnodeHeaders() });
    
    return tre; 
  }
  UpdatePass(url: string, payload: any) {
    let tre =  this.httpClient.post(`${environment.backendHost}${url}`, payload,{ headers: this.getnodeHeaders() });
    
    return tre; 
  }

//  **************************************
//  *                                    *
//  *      Develop by Abhishek           *
//  *                                    *
//  **************************************


//<------------- START------------->
  getEndUSerAndDealer(url: string){
    return this.httpClient.get(`${environment.backendHost}`+`getEndUSerAndDealer`, { headers:  this.getnodeHeaders() });
  }


  getpiechartData(url: string){
    return this.httpClient.get(`${environment.backendHost}`+`getCountperUser`, { headers:  this.getnodeHeaders() });
  }


  
  postDeviceNearExpeiry(url:string){
    return this.httpClient.get(`${environment.backendHost}${url}`, { headers: this.getnodeHeaders() })
  }


  getDeviceNearExpeiry(url:string){
    return this.httpClient.get(`${environment.backendHost}${url}`, { headers: this.getnodeHeaders() })
  }


  postAssignDevice(url: string, payload:any){
    return this.httpClient.post(`${environment.backendHost}${url}`,payload,{headers: this.getnodeHeaders()})
  }


  
  getsaleDeviceCustomerList(url:string){
    return this.httpClient.get(`${environment.backendHost}${url}`, { headers: this.getnodeHeaders() })
  }

  getAssignDeviceData(url: string, payload:any){
    return this.httpClient.post(`${environment.backendHost}${url}`,payload,{headers: this.getnodeHeaders()})
  }

  onlineDevice(url:string){
    return this.httpClient.get(`${environment.backendHost}${url}`, { headers: this.getnodeHeaders() })
  }
  

  getInventoryData(url: string, payload:any){
    return this.httpClient.post(`${environment.backendHost}${url}`,payload,{headers: this.getnodeHeaders()})
  }


  //<------------- END------------->
  

  ValidateToken(url: string, payload: any){
    console.log("yash");
    
    console.log(this.getHeaders());
    
    return this.httpClient.post(`${environment.backendHost}${url}`, payload,{ headers: this.getnodeHeaders() });
  }


  postExpeiryDeviceData(url: string, payload:any){
    return this.httpClient.post(`${environment.backendHost}${url}`,payload,{headers: this.getnodeHeaders()})
  }
  
  getUserNameRole(url:string){
    return this.httpClient.get(`${environment.backendHost}${url}`, { headers: this.getnodeHeaders() })
  }


 getHost() {
    return `${environment.host}` ;
  }

  public generate(): string {
    let isUnique = false;
    let tempId = '';

    while (!isUnique) {
      tempId = this.generator();
      if (!this.idExists(tempId)) {
        isUnique = true;
        this.ids.push(tempId);
      }
    }

    return tempId;
  }

  public remove(id: string): void {
    const index = this.ids.indexOf(id);
    this.ids.splice(index, 1);
  }

  public generateSupportSeq(url:any, payload:any){
    return this.httpClient.post(`${environment.backendHost}${url}`, payload,{ headers: this.getnodeHeaders() });
  }

  private generator(): string {
    const isString = `${this.S4()}${this.S4()}-${this.S4()}-${this.S4()}-${this.S4()}-${this.S4()}${this.S4()}${this.S4()}`;

    return isString;
  }

  private idExists(id: string): boolean {
    return this.ids.includes(id);
  }

  private S4(): string {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }

  public sendMail(url: string, payload: any) {
        //call Send mail API for sending mai/

    return this.httpClient.post(`${environment.mail}${url}`, payload, { headers: this.getHeaders() });
  
  }

  logoutUser() {
    this.cookieService.deleteAll();
    sessionStorage.clear()
    localStorage.clear()
    this.router.navigate(['/login']);
  }


}
