<!--
// Copyright © 2025 Hardcore Engineering Inc.
//
// Licensed under the Eclipse Public License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. You may
// obtain a copy of the License at https://www.eclipse.org/legal/epl-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
-->
<script lang="ts">
  import { Card } from '@hcengineering/card'
  import { getCurrentEmployee } from '@hcengineering/contact'
  import { getEmbeddedLabel } from '@hcengineering/platform'
  import { createQuery, getClient } from '@hcengineering/presentation'
  import { Execution, ExecutionStatus, ProcessToDo } from '@hcengineering/process'
  import { Button } from '@hcengineering/ui'
  import process from '../plugin'

  export let card: Card

  let docs: Execution[] = []
  let todos: ProcessToDo[] = []

  const executionQuery = createQuery()
  executionQuery.query(
    process.class.Execution,
    {
      card: card._id,
      status: { $ne: ExecutionStatus.Cancelled }
    },
    (res) => {
      console.log(res)
      docs = res
    }
  )

  const emp = getCurrentEmployee()

  const query = createQuery()
  $: query.query(
    process.class.ProcessToDo,
    {
      execution: { $in: docs.map((d) => d._id) },
      user: emp,
      doneOn: null
    },
    (res) => {
      todos = res
    }
  )

  const client = getClient()

  async function checkTodo (todo: ProcessToDo) {
    await client.update(todo, {
      doneOn: new Date().getTime()
    })
  }
</script>

{#each todos as todo (todo._id)}
  <Button kind={'primary'} label={getEmbeddedLabel(todo.title)} on:click={() => checkTodo(todo)} />
{/each}
