const template = html`
  <span>
    <!-- Button trigger modal -->
    <a data-toggle="modal" :data-target="'#'+id">
      <span v-if="isnew">add new new</span>
      <span v-if="!isnew">update</span>
    </a>

    <!-- Modal -->
    <div
      class="modal fade"
      :id="id"
      tabindex="-1"
      role="dialog"
      :aria-labelledby="id+'Label'"
      aria-hidden="true"
    >
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" :id="id+'Label'">
              <span v-if="isnew">new</span>
              <span v-if="!isnew">update</span> time log
            </h5>
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <p>{{oldtime}}</p>
            <p>{{type}}</p>
            <input type="time" required v-model="timeString" />
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-danger" data-dismiss="modal">
              cancel
            </button>
            <button type="button" class="btn btn-primary" @click="save()">
              add
            </button>
          </div>
        </div>
      </div>
    </div>
  </span>
`;
import apiV2 from "../../apiV2.js";

export default {
  props: ["id", "userId"],
  data: function () {
    return {
      // id: Math.random()
      //   .toString(36)
      //   .substring(7),
      timeString: "00:00",
      oldtime: "00:00",
      isnew: false,
      lunch: false,
      type: "in"
    };
  },
  mounted() {
    if (!this.id) return;
    if (!this.userId) return;
    this.isnew = false;
    // if (this.isnew) {
    //   this.time.set({ hour: 0, minute: 0, second: 0, millisecond: 0 });
    // }

    const timeLog = state.state[`hr/timeLog/${this.userId}`].data.find(el => {
      return el.id == this.id;
    });
    this.time = moment(timeLog.time);
    this.type = timeLog.type;

    this.timeString = this.time.format("hh:mm");
    this.oldtime = this.time.format("hh:mm");
  },
  components: {},
  filters: {},
  methods: {
    async save() {
      const newTime = this.timeString.split(":");
      const data = {
        time: this.time
          .clone()
          .set({
            hour: newTime[0],
            minute: newTime[1],
            second: 0,
            millisecond: 0
          })
          .format("YYYY-MM-DD HH:mm:ss"),
        type: this.type
      };
      const output = await apiV2.put[`hr/time-log/${this.id}`]({}, data);

      const timeLogs = await apiV2.get["hr/time-log/"]({
        user_id: this.userId
      });
      state.set(`hr/timeLog/${this.userId}`, timeLogs);
      $(`#${this.id}`).modal("hide");
    }
  },
  template
};
