import gql from 'graphql-tag'

import { client } from '@operato/graphql'
import { gqlBuilder } from '@things-factory/utils'

export async function fetchBoardTemplateList(listParam = {}) {
  const response = await client.query({
    query: gql`
      {
        boardTemplates(${gqlBuilder.buildArgs(listParam)}) {
          items {
            id
            name
            description
            thumbnail
            visibility
            createdAt
            updatedAt
          }
          total
        }
      }
    `
  })

  return response.data
}

export async function fetchBoardTemplate(id) {
  const response = await client.query({
    query: gql`
      query FetchBoardTemplate($id: String!) {
        boardTemplate(id: $id) {
          id
          name
          description
          thumbnail
          model
          visibility
          createdAt
          creator {
            id
            name
          }
          updatedAt
          updater {
            id
            name
          }
        }
      }
    `,
    variables: { id }
  })

  return response.data
}

export async function createBoardTemplate(boardTemplate) {
  /*
    input NewBoard {
      name        : String!
      description : String
      model       : String!
      visibility  : String!
    }
  */

  boardTemplate.model = JSON.stringify(boardTemplate.model)

  const response = await client.mutate({
    mutation: gql`
      mutation CreateBoardTemplate($boardTemplate: NewBoardTemplate!) {
        createBoardTemplate(boardTemplate: $boardTemplate) {
          id
          name
          description
          model
          visibility
          createdAt
          updatedAt
        }
      }
    `,
    variables: {
      boardTemplate
    }
  })

  return response.data
}

export async function updateBoardTemplate(boardTemplate) {
  /*
    input BoardPatch {
      name        : String
      description : String
      model       : String
      visibility  : String
    }
    */
  var { id, name, description, model, visibility } = boardTemplate
  model = JSON.stringify(model)

  const response = await client.mutate({
    mutation: gql`
      mutation UpdateBoard($id: String!, $patch: BoardTemplatePatch!) {
        updateBoard(id: $id, patch: $patch) {
          id
          name
          description
          model
          visibility
          createdAt
          updatedAt
        }
      }
    `,
    variables: {
      id,
      patch: { name, description, model, visibility }
    }
  })

  return response.data
}

export async function deleteBoardTemplate(id) {
  const response = await client.mutate({
    mutation: gql`
      mutation ($id: String!) {
        deleteBoardTemplate(id: $id)
      }
    `,
    variables: {
      id
    }
  })

  return response.data
}
