import {Injectable} from '@angular/core';
import {ICollection, ISchema, Resource, Service} from 'ngx-jsonapi';
import {Permission, PermissionsService} from './permissions.service';
import {Base} from 'ngx-jsonapi/services/base';


@Injectable()
export class RolesService extends Service<Role> {
  public resource = Role;
  public type = 'roles';
  public schema: ISchema = {
    relationships: {
      permissions: {
        hasMany: true
      }
    }
  };

}


export class Role extends Resource {
  public attributes: {
    name: string;
    slug: string;
  };


  get name(): string {
    return this.attributes.name;
  }

  set name(name: string) {
    this.attributes.name = name;
  }

  get slug(): string {
    return this.attributes.slug;
  }

  set slug(slug: string) {
    this.attributes.slug = slug;
  }

// ina vase relation permision hastan ke chand be chand hast
  get permissions(): ICollection<Permission> {
    return <ICollection<Permission>>this.relationships.permissions.data;
  }

  set permissions(permisssions: ICollection<Permission>) {
    this.relationships.permissions.data = permisssions;
  }

  get permissionsIds(): string[] {
    const ids: string[] = [];
    Base.forEach(this.permissions, (permission: Permission) => {
      ids.push(permission.id);
    });
    return ids;
  }

  set permissionsIds(ids: string[]) {
    const selected_permissions: ICollection<Permission> = Base.newCollection<Permission>();
    for (const key in ids) {
      if (key in ids) {
        const permission_id = ids[key];
        const permissionsService = new PermissionsService();
        const permission = permissionsService.new();
        permission.id = permission_id;
        selected_permissions[permission_id] = permission;
      }
    }
    this.permissions = selected_permissions;
  }

}
