
(function () {
  "use strict";

  // ------------------- 詳細画面表示時の処理 -------------------
  kintone.events.on('mobile.app.record.detail.show', function (event) {
    const area = kintone.mobile.app.record.getSpaceElement('header-clocking-btn-area');

    const clockIn = createBtn('clock-in', '登園', dateToFieldInDetail('登園時刻'));
    const clockOut = createBtn('clock-out', '帰園', dateToFieldInDetail('帰園時刻'));
    area.appendChild(clockIn);
    area.appendChild(clockOut);

    hideSpaceField(['clock-in-btn-area', 'clock-out-btn-area']);
    return event;
  });

  function dateToFieldInDetail(fieldCode) {
    return async function (e) {
      await new KintoneRestAPIClient().record.updateRecord({
        app: kintone.mobile.app.getId(),
        id: kintone.mobile.app.record.getId(),
        record: {
          [fieldCode]: {
            value: getCurrentTime()
          }
        }
      });
      location.reload();
    }
  }


  // ------------------- 編集画面表示時の処理 -------------------
  kintone.events.on(['mobile.app.record.create.show', 'mobile.app.record.edit.show'], function (event) {
    const clockIn = createBtn('clock-in', '登園', dateToFieldInEdit('登園時刻'));
    kintone.mobile.app.record.getSpaceElement('clock-in-btn-area').appendChild(clockIn);
    const clockOut = createBtn('clock-out', '帰園', dateToFieldInEdit('帰園時刻'));
    kintone.mobile.app.record.getSpaceElement('clock-out-btn-area').appendChild(clockOut);
    return event;
  });

  function dateToFieldInEdit(fieldCode) {
    return function (e) {
      var record = kintone.mobile.app.record.get();
      record['record'][fieldCode]['value'] = getCurrentTime();
      kintone.mobile.app.record.set(record);
    }
  }

  function getCurrentTime() {
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    return `${hours}:${minutes}`;
  }
})();