import { Server, ServerCredentials, loadPackageDefinition } from "@grpc/grpc-js";
import { loadSync } from "@grpc/proto-loader";
import moment from "moment";

// Ler as definições do protobuffer
const tasksDefs = loadSync("./tasks.proto"); 
const usersDefs = loadSync("./tasks.proto"); 

const definition = {
  ...tasksDefs, 
  ...usersDefs
}

const tasksProto = loadPackageDefinition(definition);

const tasks = [
  { 
    id: 1, 
    title: "Tarefa 01", 
    type: "IFMS", 
    created_at: "este" 
  }  
]

// Criando nosso objeto Servidor
const grpcServer = new Server();
grpcServer.addService(tasksProto.TaskService.service, {
  findAll: (call, callBack) => {
    callBack(null, { tasks: tasks })
  },

  insertOne: (call, callBack) => {
    const obj = call.request
    tasks.push(obj)
    callBack(null, obj)
  }
})

const serverAddress = '0.0.0.0:5050';
grpcServer.bindAsync(serverAddress, ServerCredentials.createInsecure(), () => {
  console.log("Servidor está funcionando bem...")
})
