

const Link = use('App/Models/Link');
class UserChildUtils {
  static async isUserConnectedToChild(user_id, child_id) {
    const links = await Link.query().where({user_id, child_id}).fetch();
    return !!links.rows.length;
  }

  static async isParentOf(user_id, child_id) {
    const links =
        await Link.query().where({user_id, child_id, is_parent: true}).fetch();
    return !!links.rows.length;
  }

  static async getChildParents(child_id) {
    const links = await Link.query().where({child_id, is_parent: true}).fetch();
    const parents = await Promise.all(links.rows.map(async l => {
      return l.user().fetch();
    }));
    return parents;
  }

  static async getUserConnections(user_id) {
    const links = await Link.query().where({user_id}).fetch();
    const connections = await links.rows.reduce(async (_prev, link) => {
      const prev = await _prev;
      const is_parent = link.is_parent;
      const child = await link.child().fetch();
      if (is_parent) {
        const parents = await UserChildUtils.getChildParents(child.id);
        const nonSameUserParents = parents.filter(p => p.id != user_id);
        prev.children.push({
          ...child.toJSON(),
          connections: [
            ...await UserChildUtils.getChildConnections(child.id),
            ...nonSameUserParents
          ]
        })
      } else {
        prev.connections.push({
          ...child.toJSON(),
          connections: [...await UserChildUtils.getChildParents(child.id)]
        })
      }
      return prev;
    }, Promise.resolve({children: [], connections: []}));
    return connections;
  }

  static async getChildConnections(child_id) {
    const links =
        await Link.query().where({child_id, is_parent: false}).fetch();
    const connections = await Promise.all(links.rows.map(async l => {
      return l.user().fetch();
    }));
    return connections;
  }
  static async addConnection(child_id, user_id, is_parent = false) {
    const link = await Link.create({child_id, user_id, is_parent});
    const user = await link.user().fetch();
    const child = await link.child().fetch();
    return {
      user, child, is_parent
    }
  }
}

module.exports = UserChildUtils;
