<template>
  <div class="account-list">
    <div class="columns is-centered is-multiline" v-if="accounts.length">
      <div class="column is-2" v-for="(account, k) in accounts" :key="k">
        <div class="box" :style="getColor(account.color)" @click="goToAccount(account._id)">
          <router-link
            :class="{ 'is-primary': !account.color, 'is-white': account.color }"
            :style="`color: ${findDarkValue(account.color)}`"
            :to="{ name: 'account', params: { id: account._id } }"
          >{{ account.name }}</router-link>
          <div v-if="account.isPublic">
            <awe-icon icon="users" />
          </div>
          <hr v-else />
          {{ account.users && account.users.map(u => u.alias).join(', ') }}
        </div>
      </div>
    </div>
    <div v-else-if="fetched">
      <awe-icon icon="inbox" />Les comptes s'afficheront ici.
    </div>
    <fab-button :to="{ name: 'account-new' }" v-if="user" :margin="true">
      <span slot="fulltext">créer un compte</span>
    </fab-button>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'
import { Getter } from 'vuex-class'
import { findDarkValue } from '@/utils'
import bus, { SYNC } from '@/utils/bus-event'
import accountService from '@/services/AccountService'
import IAccount from '@/models/IAccount'
import IColor from '@/models/IColor'
import IUser from '@/models/IUser'
import FabButton from '@/components/FabButton.vue'

@Component({
  components: {
    'fab-button': FabButton
  }
})
export default class AccountList extends Vue {
  @Getter
  public user!: IUser | null
  @Prop({ type: Boolean, default: false })
  public archived!: boolean

  public accounts: IAccount[] = []
  public fetched: boolean = false
  public textColor: string = ''
  public async created(): Promise<void> {
    this.getData()
    bus.$on(SYNC, this.getData)
  }

  public async getData(): Promise<void> {
    this.accounts = await accountService.getAll(this.archived)
    this.fetched = true
  }

  public getColor(color: string | null): any | null {
    if (!color) {
      return null
    }
    return {
      backgroundColor: color,
      color: this.findDarkValue(color)
    }
  }

  public findDarkValue(color: string): string | null {
    return findDarkValue(color)
  }

  public goToAccount(id: string): void {
    this.$router.push({ name: 'account', params: { id } })
  }
}
</script>

<style lang="scss" scoped>
@import '../styles/variables';

.box {
  border-radius: 8px;
  word-wrap: break-word;
  hyphens: auto;

  a {
    font-size: 1.2rem;
    color: $main;
  }
}

li {
  margin-bottom: 10px;
  &:last-child {
    margin-bottom: 0;
  }
}

.box {
  &:hover {
    cursor: pointer;
  }
}
</style>
