import { reactive, watch } from 'vue'
import storejs from 'store'
import deepClone from '/src/helpers/deep-clone'

const initState = {
  list: [] as any[],
  params: {
    page: 1,
    rows: 10
  },
  error: false,
  levelId: 0,
  typeId: 0,
  levelOptions: [] as any[],
  typeOptions: null as null | any[],
  finished: false,
  loading: false,
  search: '',
  subjectId: 0,
  parentId: 1
}

export const getInitState = () => deepClone(initState)

const state = reactive(getInitState())

watch(state, () => {
  storejs.set('state', state)
})

export const save = () => {
  storejs.set('state', state)
}

export const sync = () => {
  const oldState = storejs.get('state')
  if (oldState) {
    for (const key in oldState) {
      if (Object.prototype.hasOwnProperty.call(oldState, key)) {
        const item: any = oldState[key];
        (state as any)[key] = item
      }
    }
  }
}

// window.addEventListener('storage', evt => {
//   sync()
// })

export default state
