import { Injectable } from '@angular/core';
import { ApiService } from './api.service';
import { AuthService } from './auth.service';
import { StorageService } from './storage.service';

@Injectable({
  providedIn: 'root',
})
export class SettingService {
  user?: Auth.User;

  usersOfCurrentCompany: Auth.User[] = [];

  get userCompany() {
    return this.user?.company || '';
  }

  private _initialized = false;

  constructor(
    private readonly api: ApiService,
    private readonly storage: StorageService,
    private readonly auth: AuthService
  ) {}

  clear() {
    this._initialized = false;
    this.user = undefined;
  }
  async getUsersOfCurrentCompany() {
    this.usersOfCurrentCompany = await this.api.user.getAllUserByCompany(this.userCompany);
  }
  async init(): Promise<boolean> {
    if (this._initialized) {
      return true;
    }

    if (!this.auth.autoLogin()) {
      return false;
    }

    return this.onInit().catch(err => {
      console.error('init error', err);
      return false;
    });
  }

  private async onInit() {
    await this.fetchUserInfo();
    this._initialized = true;
    return true;
  }
  async fetchUserInfo() {
    // this.storage.
    const info = await this.api.user.getMyInfo();
    this.user = info;
  }

  updateUser(data: Auth.ModifyUserInfo) {
    // return this.api.user.modifyMyInfo(data);
  }
}
