<template>
  <Authenticated>
    <div class="flex">
      <div class="column">
        <div v-if="group">
          <h2>Currency</h2>
          <p>{{ group.currency }}</p>
        </div>

        <div v-if="group && group.description">
          <h2>Description</h2>
          <p>{{ group.description }}</p>
        </div>

        <h2>Members</h2>
        <ul>
          <li v-for="member in members" :key="member.id">
            <UserLink :name="member.name"/>
          </li>
        </ul>

        <form v-if="group && !group.closed" v-on:submit.prevent="addMember">
          <label for="userName">Add user</label>
          <input id="userName"
                 type="text"
                 v-model="memberForm.userName"
                 v-on:input="getAutocompletedUsers()"
                 autocomplete="off"
                 list="userAutocomplete"
                 required
          />
          <datalist id="userAutocomplete">
            <option v-for="user in autocompletedUsers" :key="user.id">
              {{ user.name }}
            </option>
          </datalist>
          <Button type="submit">Add member</Button>
          <div>{{ memberForm.responseMessage }}</div>
        </form>
      </div>

      <div class="column">
        <div>
          <h2>Expenses</h2>
          <table v-if="expenses.length" id="table-overview">
            <thead>
            <tr>
              <th>Date</th>
              <th>Description</th>
              <th>Buyer</th>
              <th>Amount</th>
              <th></th>
            </tr>
            </thead>
            <tr v-for="expense in expenses" :key="expense.id">
              <td>{{ expense.creationDate.toDateString() }}</td>
              <td>{{ expense.description }}</td>
              <td>
                <UserLink :name="expense.creator.name"/>
              </td>
              <td>
                {{ expense.integerAmount }}.{{ expense.fractionAmount }}
              </td>
              <td>
                <Button v-if="!group.closed" v-on:click.native="removeExpense(expense.id)">Remove</Button>
              </td>
            </tr>
          </table>
        </div>
        <div v-if="group && !group.closed">
          <h2>Create Expense</h2>
          <div>
            <form v-if="group && !group.closed" v-on:submit.prevent="addExpense">
              <label>
                Description
                <input type="text" v-model="expenseForm.description" required/>
              </label>
              <label>
                Amount
                <input
                    v-model="expenseForm.amount"
                    type="number"
                    placeholder="1.00"
                    step="0.01"
                    min="0"
                    required
                />
              </label>
              <Button type="submit">Create expense</Button>
            </form>
            <br/>
          </div>
        </div>
        <div v-if="group && group.closed">
          <h2>Settlements</h2>
          <ul>
            <li v-for="(settlement, index) in settlements" :key="index">
              <UserLink :name="settlement.from"/>
              to
              <UserLink :name="settlement.to"/>
              {{ settlement.integerAmount }}.{{ settlement.fractionAmount }}
            </li>
          </ul>
        </div>
      </div>
    </div>
    <Button v-if="group && !group.closed" v-on:click.native="closeGroup()">Close group</Button>
  </Authenticated>
</template>

<script>
import { fetchData, getJson, postAndGetJson, postJson } from "@/util/fetch";
import Authenticated from "@/components/Authenticated";
import Button from "@/components/Button";
import UserLink from "@/components/UserLink";

export default {
  components: { UserLink, Button, Authenticated },
  data() {
    return {
      name: this.$route.params.name,
      group: undefined,
      members: [],
      expenses: [],
      settlements: undefined,
      memberForm: {
        userName: "",
        responseMessage: undefined,
      },
      expenseForm: {
        description: undefined,
        amount: undefined,
      },
      autocompletedUsers: [],
    };
  },
  methods: {
    addMember() {
      postAndGetJson(`${this.$router.currentRoute.path}/member`, {
        name: this.memberForm.userName,
      }).then((response) => {
        if (response.message)
          this.memberForm.responseMessage = response.message;
        this.getMembers();
      });
    },
    addExpense() {
      const amount = Math.round(100 * parseFloat(this.expenseForm.amount));

      postAndGetJson(`${this.$router.currentRoute.path}/expense`, {
        description: this.expenseForm.description,
        amount,
      }).then(() => this.getExpenses());
    },
    removeExpense(id) {
      fetchData(`${this.$router.currentRoute.path}/expense/${id}`, {
        method: "DELETE",
      }).then(() => {
        this.getExpenses();
      });
    },
    getGroupAndSettlements() {
      getJson(`/group/${this.name}`).then((group) => {
        this.group = group;
        if (group.closed) {
          getJson(`/group/${this.name}/settlements`).then(settlements => {
            this.settlements = settlements.map((s) => {
              this.convertAmountToIntegerAndFraction(s.amount);
              const converted = this.convertAmountToIntegerAndFraction(s.amount);
              delete s.amount;

              s.integerAmount = converted.integerAmount;
              s.fractionAmount = converted.fractionAmount;
              return s;
            });
          });
        }
      });
    },
    getMembers() {
      getJson(`/group/${this.name}/members`).then(members => this.members = members);
    },
    getExpenses() {
      getJson(`/group/${this.name}/expenses`).then(expenses => {
        this.expenses = expenses.map((e) => {
          const converted = this.convertAmountToIntegerAndFraction(e.amount);
          e.integerAmount = converted.integerAmount;
          e.fractionAmount = converted.fractionAmount;
          e.creationDate = new Date(e.creationDate);
          return e;
        });
      });
    },
    closeGroup() {
      postJson(`/group/${this.name}/close`).then(() =>
          this.getGroupAndSettlements()
      );
    },
    convertAmountToIntegerAndFraction(amount) {
      return {
        integerAmount: Math.floor(amount / 100),
        fractionAmount: amount % 100,
      };
    },
    getAutocompletedUsers() {
      const name = this.memberForm.userName;
      getJson(`/users?startsWith=${name}&limit=5`).then(
          (users) => (this.autocompletedUsers = users)
      );
    },
  },
  created() {
    this.getGroupAndSettlements();
    this.getMembers();
    this.getExpenses();
    this.getAutocompletedUsers();
  },
};
</script>

<style scoped>
.flex {
  width: 60vw;
  display: flex;
  flex-direction: row;
}

div.column {
  flex-grow: 1;
  flex-direction: column;
  display: flex;
}

div.column > div, ul {
  margin: 0.5em 0 1em 0;
}

#table-overview {
  border-collapse: collapse;
  text-align: left;
}

#table-overview > td,
th {
  border-bottom: 1px solid rgb(173, 171, 171);
  border-collapse: collapse;
}

th {
  padding-bottom: 15px;
}

tr {
  border-bottom: 1px solid rgb(173, 171, 171);
}

tr:nth-child(even) {
  background: #d72765;
}

td {
  padding: 4px;
}
</style>
