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

import {User, UsersService} from '../components/user/users/users.service';
import {App, AppsService} from './apps.service';


@Injectable()
export class MessageService extends Service<Message> {
  public resource = Message;
  public type = 'messages';
  public schema: ISchema = {
    relationships: {
      apps: {
        hasMany: true
      },
      receivers: {
        hasMany: true
      },
    }
  };
}


export class Message extends Resource {
  public attributes: {
    title: string;
    body: string;
    send_type: string;
  };

  get title() {
    return this.attributes.title;
  }

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

  get body() {
    return this.attributes.body;
  }

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

  get send_type() {
    return this.attributes.send_type;
  }

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

  // baray relationship app ke chand be chand hast

  get apps(): ICollection<App> {
    return <ICollection<App>>this.relationships.apps.data;
  }

  set apps(apps: ICollection<App>) {
    this.relationships.apps.data = apps;
  }

  get appsIds(): string[] {
    let ids: string[] = [];
    Base.forEach(this.apps, (app: App) => {
      ids.push(app.id);
    });
    return ids;
  }

  set appsIds(ids: string[]) {
    let selected_apps: ICollection<App> = Base.newCollection<App>();
    ids.forEach(function (id) {
      let app = (new AppsService()).new();
      app.id = id;
      selected_apps[id] = app;
    });
    this.apps = selected_apps;
  }

  // baray relationship receiver hast ke chand be chande
  get receivers(): ICollection<User> {
    return <ICollection<User>>this.relationships.receivers.data;
  }

  set receivers(user: ICollection<User>) { // todo
    this.relationships.receivers.data = user;
  }

  get receiversIds(): string[] {
    let ids: string[] = [];
    Base.forEach(this.receivers, (user: User) => {
      ids.push(user.id);
    });
    return ids;
  }


  set receiversIds(ids: string[]) {
    let selected_users: ICollection<User> = Base.newCollection<User>();
    ids.forEach(function (id) {
      let user = (new UsersService()).new();
      user.id = id;
      selected_users[id] = user;
    });
    this.receivers =  selected_users
  }
}
