import { Injectable } from "@angular/core";
import { Http, Headers, ResponseContentType } from "@angular/http";

@Injectable()
export class HttpService {
  // _url = "https://localhost:44306/api";

  _url = "https://172.16.1.49:8443/violation/api";
  // _url = "https://carviolation.tycg.gov.tw:8443/violation/api";

  _token = "";
  _role = "";
  _id = "";
  _permissions: string[] = [];
  blob: Blob;
  constructor(private http: Http) {
    this.setToken(localStorage.getItem("token")),
      this.setPermission(JSON.parse(localStorage.getItem("pages"))),
      this.setRole(JSON.parse(localStorage.getItem("role")));
  }

  createAuthorizationHeader(headers: Headers) {
    if (this._token) {
      headers.append("Authorization", "Bearer " + this._token);
    }
  }

  setToken(token) {
    this._token = token;
  }

  setRole(role) {
    this._role = role;
  }

  setId(id) {
    this._id = id;
  }

  setPermission(permissions) {
    this._permissions = permissions;
  }
  isAvailableLink(link) {
    return this._permissions.indexOf(link) > -1;
  }

  get(path) {
    const fullPath = `${this._url}${path}`;
    const headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.get(fullPath, { headers: headers });
  }

  getDownload(path) {
    const fullPath = `${this._url}${path}`;
    const headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.get(fullPath, { headers: headers } );
  }

  post(path, data) {
    const fullPath = `${this._url}${path}`;
    const headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.post(fullPath, data, { headers: headers });
  }

  put(path, data) {
    const fullPath = `${this._url}${path}`;
    const headers = new Headers();
    this.createAuthorizationHeader(headers);
    headers.append("Content-Type", "application/json");
    return this.http.put(fullPath, data, { headers: headers });
  }

  delete(path) {
    const fullPath = `${this._url}${path}`;
    const headers = new Headers();
    this.createAuthorizationHeader(headers);
    headers.append("Content-Type", "application/json");
    return this.http.delete(fullPath, { headers: headers });
  }

  upload(path, file: FormData) {
    const fullPath = `${this._url}${path}`;
    const headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.post(fullPath, file, { headers: headers });
  }
}
