import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import "rxjs/add/operator/map";

@Injectable()
export class ProfileService {
  endpoint: string = "http://localhost:27017/urnings/profiles";
  fallback: string = "assets/data/profiles.json";
  epSubmitted: string = "/submitted";
  epVerified: string = "/verified";
  idMap: any = { all: {}, submitted: {}, verified: {} };
  profiles: any;

  constructor(private http: Http) {
    this.idMap = { all: {}, submitted: {}, verified: {} };
    this.profiles = null;
  }

  load() {
    if (this.profiles) {
      return Promise.resolve(this.profiles);
    }

    return new Promise((resolve) => {
      this.doGetRequest(this.endpoint, resolve);
    });
  }

  loadSubmitted() {
    if (this.profiles && this.profiles.submitted) {
      return Promise.resolve(this.profiles.submitted);
    }

    return new Promise((resolve) => {
      this.doGetRequest(this.endpoint + this.epSubmitted, resolve, "submitted");
    });
  }

  loadVerified() {
    if (this.profiles && this.profiles.verified) {
      return Promise.resolve(this.profiles.verified);
    }

    return new Promise((resolve) => {
      this.doGetRequest(this.endpoint + this.epVerified, resolve, "verified");
    });
  }

  doGetRequest(endpoint, resolve, type = "all") {
    this.http
      .get(endpoint)
      .map((res) => res.json())
      .subscribe(
        (data) => {
          this.profiles = this.profiles || {};
          this.profiles[type] = data;
          this.profiles[type].reduce((map, profile, i) => {
            console.log("profile: ", { map, profile, i });
            map[profile._id] = i;
            return map;
          }, this.idMap[type]);
          resolve(this.profiles[type]);
        },
        (error) => {
          this.doGetRequest(this.fallback, resolve, type);
        }
      );
  }

  getNextProfile(id, type = "all") {
    var nextIdIndex = this.idMap[type][id] + 1;
    nextIdIndex = nextIdIndex >= this.profiles[type].length ? 0 : nextIdIndex;
    return this.profiles[type][nextIdIndex];
  }

  getPreviousProfile(id, type = "all") {
    var prevIdIndex = this.idMap[type][id] - 1;
    prevIdIndex =
      prevIdIndex < 0 ? this.profiles[type].length - 1 : prevIdIndex;
    return this.profiles[type][prevIdIndex];
  }

  getProfiles() {
    return this.profiles.all;
  }

  getProfileById(id) {
    return this.profiles[this.idMap[id]];
  }

  getSubmittedProfiles() {
    return this.profiles.submitted;
  }

  getVerifiedProfiles() {
    return this.profiles.verified;
  }
}
