import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';
import { apiConfig } from '../../environments/server.config';
import { SubjectService } from './subject.service';
import { Router, ActivatedRoute } from '@angular/router';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Auth': 'my_key'
  })
};

const httplive = {
  headers: new HttpHeaders({
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
    'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization'
  })
};

@Injectable({
  providedIn: 'root'
})

export class WebService {
  constructor(private http: HttpClient, public subjectService: SubjectService, private router: Router) {
  }

  post_data(url: string, data) {
    return this.http.post(`${apiConfig + url}`, data).pipe(map((response: any) => response));
  }
  get_data(url) {
    return this.http.get(`${apiConfig + url}`).pipe(map((response: any) => response));
  }
  setLocalStorageItem(id: string, data: string) {
    localStorage.setItem(id, data);
  }
  getLocalStorageItem(data: string): string {
      return localStorage.getItem(data);
  }
  removeLocalStorageItem(data) {
    localStorage.removeItem(data);
    localStorage.clear();
  }

  ObjArray(data: any) {
    if (data instanceof Array !== true) {
      if (data !== undefined) {
        return new Array(data);
      } else {
        return undefined;
      }
    } else {
      return data;
    }
  }

  logout() {
    const userData = this.getLocalStorageItem('userData');
    this.removeLocalStorageItem(userData);
    this.subjectService.sendLoginData('logged_out');
    this.router.navigate(['/start/login']);
  }


}
