'use strict'
const {validate, rule} = use('Validator');
const User = use('App/Models/User');
const Child = use('App/Models/Child')
const Link = use('App/Models/Link');
// import FileUtils from '../../Utils/FileUtils';
const FileUtils = use('App/Utils/FileUtils');

class ClientApiController {
  async getConnections({request, auth, response}) {
    try {
      const user = auth.user;
      const userLinks = (await user.links().fetch()).rows;
      // console.log(userLinks.toJSON());
      let links = Promise.resolve({});
      const result = await Promise.all(userLinks.map(async (l) => {
        const child = await l.child().fetch();
        const is_parent = !!l.is_parent;
        const childLinks = (await child.links().fetch())
                               .rows.filter(l => l.user_id != user.id);
        const linkedUsers = await Promise.all(childLinks.map(async l => {
          return (await l.user().fetch()).toJSON();
        }));
        return {
          ...child.toJSON(), linkedUsers, is_parent
        }
      }));
      return result;
    } catch (err) {
      console.error(err);
      response.send(err.message);
    }
  }

  async getUser({auth}) {
    const user = auth.user.toJSON();
    const children = await Promise.all((await auth.user.links().fetch())
                                           .rows.filter(l => l.is_parent)
                                           .map(async (l) => {
                                             return await l.child().fetch();
                                           }));
    return {
      ...user, children
    }
  }

  async createChild({auth, request, response}) {
    const rules = {
      name: 'required|string',
      dob: 'required|date',
      avatar: [rule('regex', /^(data:image\/\w+;base64).+/)]
    };
    const validation = await validate(request.all(), rules);
    if (validation.fails()) {
      response.status(400);
      response.send(validation.messages());
      return false;
    }
    const body = request.body;
    if (body.avatar) {
      const file = await FileUtils.saveBase64File(body.avatar);
      console.log(file);
      body.avatar = `/u/images/${file.fileName}`;
    } else {
      body.avatar =
          `https://api.adorable.io/avatars/285/${body.name.trim()}.png`;
    }
    const child = await Child.create(body);
    const link = await Link.create(
        {user_id: auth.user.id, child_id: child.id, is_parent: true});
    return child;
  }
}

module.exports = ClientApiController
