import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AccessControl } from 'accesscontrol';
import { firstValueFrom, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {


  private _ac: AccessControl = new AccessControl([
    { role: 'user', resource: 'dummy', action: 'read:own', attributes: '*' },
  ]);

  public acChange = new Subject<any>();

  set ac(ac: AccessControl) {
    this._ac = ac;
    this.acChange.next(1);
  }

  get ac() {
    return this._ac;
  }

  $ac: Promise<AccessControl>;


  constructor(private http: HttpClient) {
    this.$ac = firstValueFrom(this.getGrants())
      .then(resp => {
        let grants = grantsTransform(resp as any[]);
        console.log('grants', grants);
        return new AccessControl(grants);
      })
      .catch(err => {
        console.error('AccessControl initialze failed:', err);
        return this._ac;
      }).then(ac => {
        console.log('ac 初始化成功');
        return ac;
      })
  }



  signOut() {
    return this.http.get('/napi/web/auth/sign-out');
  }

  signIn(data) {
    return this.http.post('/napi/web/auth/sign-in', data);
  }

  guard() {
    return this.http.get('/napi/web/auth/guard');
  }

  profile() {
    return this.http.get('/napi/web/auth/profile');
  }

  getMenus() {
    return this.http.get('/napi/web/menu');
  }

  //TODO
  checkUsername(username) {
    return this.http.post('/napi/web/auth/check-username', { username });
  }

  checkPhone(phone) {
    return this.http.post('/napi/web/auth/check-phone', { phone });
  }

  getGrants() {
    return this.http.get(`/napi/web/auth/grants`);
  }

}

function grantsTransform(resp: any[]) {
  return resp.map(item => {
    let { resource, action, possession, attributes } = item;
    return {
      role: 'user',
      resource, attributes,
      action: `${action}:${possession}`,
    }
  })
}

