const template = html`
  <div class="widget widget-classic">
    <div class="widget-content">
      <div class="headline">
        <h4><i class="fa fa-clock-o"></i> Your clocking logs</h4>
      </div>

      <div class="row">
        <div class="col-sm-8">
          <!-- <h3>{{me.name}}</h3> -->
        </div>

        <div class="col-sm-4">
          <table
            class="table table-no-header table-striped-odd table-condensed"
          >
            <tbody>
              <tr>
                <td>Total hours:</td>
                <td class="ng-binding">72.49</td>
              </tr>
              <tr>
                <td>Your hourly rate:</td>
                <td class="ng-binding">
                  £6.00
                </td>
              </tr>
              <tr>
                <td>Total amount:</td>
                <td class="ng-binding">£234.90</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <input
        type="month"
        id="start"
        name="start"
        class="form-control"
        v-model="startDateString"
      />
      <table class="table table-condensed">
        <thead>
          <tr>
            <th></th>
            <th></th>
            <th></th>
            <th class="centered">
              <i class="fa fa-circle text-success"></i> Clock In
            </th>

            <th class="centered">
              <i class="fa fa-circle text-danger"></i> Clock Out
            </th>
            <th class="centered">Hours</th>
            <th class="centered">Amount</th>
            <th></th>
          </tr>
        </thead>

        <tbody>
          <template v-for="n in daysInMonth">
            <tr @click="toggle(n)">
              <td>{{n}}</td>
              <td>{{n | formatWeek(startDate) }}</td>
              <td>
                {{n}}/{{month}}/{{year}}
              </td>

              <td>{{firstClockInTime(n) }}</td>
              <td>{{lastClockOutTime(n)}}</td>
              <td>{{getDay(n).hours | round}}</td>
              <td>£{{getDay(n).amount | round}}</td>
              <td></td>
            </tr>
            <timeel
              v-for="day in getDay(n).times "
              v-if="opened.includes(n)"
              :day="day"
              :userId="userId"
              :startDate="startDate"
              :n="n"
            ></timeel>
            <tr v-if="opened.includes(n)">
              <td></td>
              <td></td>
              <td></td>
              <td>
                <newTime
                  :time="startDate.clone().add(n-1,'days')"
                  :userId="userId"
                  type="in"
                ></newTime>
              </td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
          </template>
        </tbody>
      </table>
      <button
        class="btn btn-default pull-right"
        data-ng-click="generateTimesheet()"
      >
        Generate Timesheet
      </button>
    </div>
  </div>
`;
import apiV2 from "../../apiV2.js";
import api from "../../api.js";
import state from "../../state/main.js";
import timeel from "./timeel.js";
import newTime from "./newTime.js";

export default {
  props: ["userId"],
  data: function() {
    return {
      isHidden: true,
      opened: [], // required for method: toggle()
      rate: 8,
      timeLogs: {},
      me: { name: "" },
      startDateString: moment().format("YYYY-MM")
    };
  },
  created() {
    this.load();
  },
  watch: {
    userId(val, oldVal) {
      this.load();
    }
  },
  computed: {
    daysInMonth() {
      return this.startDate.daysInMonth();
    },
    month() {
      return this.startDate.month();
    },
    year() {
      return this.startDate.year();
    },
    startDate() {
      return moment(this.startDateString).startOf("month");
    }
  },
  filters: {
    // takeout the 00-00-00 from dates
    formatDate: function(val, type) {
      return moment(val).format(type);
    },
    formatWeek(val, startDate) {
      return startDate
        .clone()
        .add(val, "day")
        .format("dddd");
    },
    formatDateTimeDiff: function(val, endTime, as) {
      var as = "asHours";
      var start = moment(val);
      var end = moment(endTime);
      var duration = moment.duration(end.diff(start));
      var time = duration[as]();
      return time.toFixed(3) * 10;
    },
    round(num) {
      return Math.round(num * 100) / 100;
    }
  },
  components: {
    timeel,
    newTime
  },
  methods: {
    firstClockInTime(n) {
      const day = this.getDay(n);
      if (!day.times || !day.times[0]) {
        return;
      }
      return moment(day.times[0].timeIn.time).format("LT");
    },
    lastClockOutTime(n) {
      const day = this.getDay(n);

      if (!day.times || !day.times[day.times.length - 1]) {
        return;
      }
      const times = day.times;
      if (!times[times.length - 1] || !times[times.length - 1].timeOut) {
        return;
      }
      return moment(times[times.length - 1].timeOut.time).format("LT");
    },
    async loadMe() {
      state.sub("me", value => (this.me = value));
      const data = await api.get.me();
      state.set("me", data);
    },
    async load() {
      const key = `hr/timeLog/${this.userId}`;
      state.sub(key, value => (this.timeLogs = value));
      const timeLogs = await apiV2.get["hr/time-log"]({
        userId: this.userId
      });
      state.set(key, timeLogs);
    },
    getDay(dayNumber) {
      if (!this["timeLogs"] || !this["timeLogs"].data) {
        return [];
      }

      let day = this["timeLogs"].data.filter(n => {
        return moment(n.time).date() == dayNumber;
      });

      let daysIn = day.filter(el => el.type == "in");
      let daysOut = day.filter(el => el.type == "out");

      let times = daysIn.map(this.calTimes.bind(this, daysOut));

      const hours = times.reduce((value, el) => el.hours + value, 0);
      const amount = times.reduce((value, el) => el.amount + value, 0);

      return { times, hours: hours, amount: amount };
    },
    calTimes(daysOut, timeIn, index) {
      let hours = 0;
      if (daysOut[index] && timeIn) {
        const part = moment(daysOut[index].time).diff(timeIn.time);
        hours = moment.duration(part).asHours();
      }
      const amount = hours * this.rate;
      return { timeIn, timeOut: daysOut[index], hours, amount };
    },
    toggle(id) {
      const index = this.opened.indexOf(id);
      if (index > -1) {
        this.opened.splice(index, 1);
      } else {
        this.opened.push(id);
      }
    }
  },
  template
};
