'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');
const Call = use('App/Models/Call');

const FileUtils = use('App/Utils/FileUtils');
const UserChildUtils = use('App/Utils/UserChildUtils');
const uuidv4 = require('uuid').v4;

class ClientApiController {
  async getUser({auth}) {
    const user = auth.user.toJSON();
    const connections = await UserChildUtils.getUserConnections(user.id);
    return {
      ...user, connections: {...connections}
    }
  }

  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;
  }

  async createCall({auth, request, response}) {
    try {
      const user = auth.user;
      const rules = {
        connection_id: 'number|required',
        child_id: 'number|required',
      };
      const validation = await validate(request.all(), rules);
      if (validation.fails()) {
        response.status(400);
        response.send(validation.messages());
        return false;
      }
      const body = request.body;
      if (!(await UserChildUtils.isParentOf(user.id, body.child_id))) {
        response.status(403);
        response.send({code: 403, message: 'Unauthorized'});
        return false;
      }
      if (!(await UserChildUtils.isUserConnectedToChild(
              body.connection_id, body.child_id))) {
        response.status(403);
        response.send({code: 403, message: 'Unauthorized'});
        return false;
      }
      const call = await Call.create({
        state: 'NEW',
        user_1: user.id,
        user_2: body.connection_id,
        child_id: body.child_id
      });
      return {
        code: 0, data: call
      }
    } catch (error) {
      console.error(error);
      return error;
    }
  }

  async getChild({auth, request, response}) {
    const userId = auth.user.id;
    const childId = request.params.id;
    console.log(`${userId} -> ${childId}`);
    const hasPermission =
        await UserChildUtils.isUserConnectedToChild(userId, childId);
    if (!hasPermission) {
      response.status(403);
      response.send(
          {code: 403, message: `You have no permission to connect with child`});
      return false;
    }
    const child = await Child.find(childId);
    const parents = await UserChildUtils.getChildParents(childId);
    const connections = await UserChildUtils.getChildConnections(childId);
    return {
      code: 0, data: {...child.toJSON(), parents, connections}
    }
  }

  async createConnection({request, auth, response}) {
    try {
      const user = auth.user;
      const rules = {
        email: 'string|email|required',
        is_parent: 'boolean|required',
        child_id: 'number|required'
      };
      const validation = await validate(request.all(), rules);
      if (validation.fails()) {
        response.status(400);
        response.send(validation.messages());
        return false;
      }
      const body = request.body;
      if (!await UserChildUtils.isParentOf(user.id, body.child_id)) {
        response.status(403);
        response.send({
          code: 403,
          message: `You have no permission to add connection to child`
        });
        return false;
      }
      const usersWithEmail =
          (await User.query().where({email: body.email}).fetch()).rows;
      if (!usersWithEmail.length) {
        return {code: 404, message: 'No user with that Email...'};
      }
      const targetUser = usersWithEmail[0];
      if (await UserChildUtils.isUserConnectedToChild(
              targetUser.id, body.child_id)) {
        return {code: 409, message: 'User already connected'};
      }
      return {
        code: 0,
        data: await UserChildUtils.addConnection(
            body.child_id, targetUser.id, body.is_parent)
      };
    } catch (error) {
      console.error(error);
      return error;
    }
    //
  }

  async setChildProfileCover({request, auth, response}) {
    try {
      const rules = {
        profile_cover: [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;
      const userId = auth.user.id;
      const childId = request.params.id;
      const isParent = await UserChildUtils.isParentOf(userId, childId);
      if (!isParent) {
        response.status(403);
        response.send(
            {code: 403, message: `You have no permission to edit this child`});
        return false;
      }
      const child = await Child.find(childId);
      const file = await FileUtils.saveBase64File(body.profile_cover);
      console.log(file);
      child.profile_cover = `/u/images/${file.fileName}`;
      await child.save();
      return child.profile_cover;

    } catch (error) {
      console.error(error);
      return error;
    }
  }
}

module.exports = ClientApiController
