import Taro from "@tarojs/taro";
import {curriculum} from "@/api";

const KEY = 'unique_ident'


/** 设置学习记录缓存 */
async function set(courseId: number) {
  Taro.removeStorageSync(KEY)
  const res = await curriculum.hourCache(courseId, {duration: 0} as HourCacheParam)
  Taro.setStorage({
    key: KEY,
    data: {
      courseId,
      duration: 0,
      end_date: 0,
      hour_id: 0,
      start_date: Date.now(),
      unique_ident: res
    }
  })
}

function remove() {
  Taro.removeStorageSync(KEY)
}

/**
 * 上传学习记录
 * @param hour_id 课时id
 * @param duration
 * @param start_date 记录当前的时间戳
 */
function put(hour_id?: number, duration?: number, start_date?: number) {
  const data: HourCacheParam | undefined = Taro.getStorageSync(KEY)
  if (data) {
    data.start_date = start_date || data.start_date
    data.duration = duration || data.duration
    data.hour_id = hour_id || data.hour_id
    Taro.setStorageSync(KEY, data)
  }
}

async function upload() {
  const data: HourCacheParam | undefined = Taro.getStorageSync(KEY)
  if (data) {
    await curriculum.commit(data.courseId, data)
  }
}

function get(): HourCacheParam | undefined {
  return Taro.getStorageSync(KEY)
}


export default {
  set,
  put,
  remove,
  upload,
  get
}
