<!--
// Copyright © 2022 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 contact, { Employee, EmployeeAccount } from '@hcengineering/contact'
  import { Account, DocumentQuery, Ref, SortingOrder, Space } from '@hcengineering/core'
  import { translate } from '@hcengineering/platform'
  import setting from '@hcengineering/setting'
  import { IconAdd, Label, SearchEdit, showPopup } from '@hcengineering/ui'
  import { createEventDispatcher } from 'svelte'
  import presentation from '../plugin'
  import { getClient } from '../utils'
  import UserInfo from './UserInfo.svelte'
  import login from '@hcengineering/login'

  export let space: Space
  export let withAddButton: boolean = false
  export let withInviteWorkspaceButton: boolean = false

  const client = getClient()
  const dispatch = createEventDispatcher()
  const hierarchy = client.getHierarchy()
  $: label = hierarchy.getClass(space._class).label
  let spaceClass = ''
  $: {
    translate(label, {}).then((p) => (spaceClass = p.toLowerCase()))
  }
  let search: string = ''
  $: isSearch = search.trim().length
  let members: Set<Ref<Employee>> = new Set<Ref<Employee>>()

  async function getUsers (accounts: Ref<Account>[], search: string): Promise<Employee[]> {
    const query: DocumentQuery<EmployeeAccount> =
      isSearch > 0 ? { name: { $like: '%' + search + '%' } } : { _id: { $in: accounts as Ref<EmployeeAccount>[] } }
    const employess = await client.findAll(contact.class.EmployeeAccount, query)
    members = new Set(employess.filter((p) => accounts.includes(p._id)).map((p) => p.employee))
    return await client.findAll(
      contact.class.Employee,
      {
        _id: { $in: employess.map((e) => e.employee) }
      },
      { sort: { name: SortingOrder.Descending } }
    )
  }

  async function add (employee: Ref<Employee>): Promise<void> {
    const account = await client.findOne(contact.class.EmployeeAccount, { employee })
    if (account === undefined) return
    await client.update(space, {
      $push: {
        members: account._id
      }
    })
  }

  function inviteWorkspace (): void {
    showPopup(login.component.InviteLink, {})
  }
</script>

<div class="flex-row-reverse mb-3 mt-3"><SearchEdit bind:value={search} /></div>
{#await getUsers(space.members, search) then users}
  {@const current = users.filter((p) => members.has(p._id))}
  {@const foreign = users.filter((p) => !members.has(p._id))}
  {#if isSearch && !foreign.length && !current.length}
    <div class="fs-title flex-center mt-10">
      <Label label={presentation.string.NoMatchesFound} />
    </div>
  {:else}
    {#if isSearch}
      <div class="pr-8 pl-8"><Label label={presentation.string.InThis} params={{ space: spaceClass }} /></div>
      {#if !current.length}
        <div class="fs-title pl-8 mb-4 mt-4">
          <Label label={presentation.string.NoMatchesInThis} params={{ space: spaceClass }} />
        </div>
      {/if}
    {/if}
    {#if !isSearch && withAddButton}
      <div class="item fs-title">
        <div class="flex-row-center" on:click={() => dispatch('addMembers')}>
          <div class="flex-center ml-1 mr-1"><IconAdd size={'large'} /></div>
          <div class="flex-col ml-2 min-w-0 content-accent-color">
            <Label label={presentation.string.Add} />
          </div>
        </div>
      </div>
    {/if}
    {#each current as person}
      <div class="item fs-title"><UserInfo size={'medium'} value={person} /></div>
    {/each}
    {#if foreign.length}
      <div class="mt-4 notIn h-full">
        <div class="divider w-full mb-4" />
        <div class="pr-8 pl-8"><Label label={presentation.string.NotInThis} params={{ space: spaceClass }} /></div>
        {#each foreign as person}
          <div class="item flex-between">
            <div class="fs-title"><UserInfo size={'medium'} value={person} /></div>
            <div class="over-underline" on:click={() => add(person._id)}>
              <Label label={presentation.string.Add} />
            </div>
          </div>
        {/each}
      </div>
    {/if}
  {/if}
{/await}
{#if withInviteWorkspaceButton}
  <div class="item fs-title mb-4 mt-2">
    <div class="flex-row-center p-1" on:click={inviteWorkspace}>
      <Label label={setting.string.InviteWorkspace} />
    </div>
  </div>
{/if}

<style lang="scss">
  .notIn {
    background-color: var(--theme-bg-accent-color);
  }

  .divider {
    background-color: var(--theme-dialog-divider);
    height: 1px;
  }

  .item {
    color: var(--caption-color);
    cursor: pointer;
    padding: 0.5rem 1rem;
    border-radius: 0.25rem;

    &:hover,
    &:focus {
      background-color: var(--popup-bg-hover);
    }
  }
</style>
