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


@Injectable()
export class PermissionsService extends Service<Permission> {
  public resource = Permission;
  public type = 'permissions';
  public schema: ISchema = {
    relationships: {
      group: {
        hasMany: false
      }
    }
  };

}

export class Permission 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;
  }

  get group(): Permission {
    return <Permission>this.relationships.group.data;
  }

  set group(group: Permission) {
    this.relationships.group.data = group;
  }

  set groupId(id: string) {
    const permissionService = new PermissionsService();
    const group = permissionService.new();
    group.id = id;
    this.group = group;
  }

}

@Injectable()
export class PermissionGroupsService extends Service<PermissionGroup> {
  public resource = PermissionGroup;
  public type = 'permission-groups';
  public schema: ISchema = {
    relationships: {
      permissions: {
        hasMany: true
      }
    }
  };


}

export class PermissionGroup 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;
  }

  get permissions(): ICollection<Permission> {
    return <ICollection<Permission>>this.relationships.permissions.data;
  }

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

  get permissionsIds(): string[] {
    let 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;
    }
  }
}
