import { deepcopy } from '@/utils/deepcopy'
import axios from 'axios'
import { defineStore } from 'pinia'

export const useConfigStore = defineStore('config', () => {
  const shop_list = ref([])

  async function load_shop() {
    const { data } = await axios.get(`${import.meta.env.VITE_HTTP_URL}/shop`)
    const mall_list = []
    for (const i of data) {
      mall_list.push({
        value: i,
        label: i
      })
    }
    shop_list.value = mall_list
  }

  const conf = ref({ webview: { scale: 1.0 } })

  const int2bool = [
    'enable_party',
    'leifeng_mode',
    'maa_enable',
    'maa_rg_enable',
    'mail_enable',
    'skland_enable'
  ]

  const str2list = ['free_blacklist', 'reload_room', 'maa_mall_buy', 'maa_mall_blacklist']

  function parse_config(data) {
    for (const i of int2bool) {
      data[i] = data[i] != 0
    }
    for (const i of str2list) {
      data[i] = data[i] == '' ? [] : data[i].split(',')
    }
    data.package_type = data.package_type == 1 ? 'official' : 'bilibili'
    data.resting_threshold = data.resting_threshold * 100
    data.tap_to_launch_game.enable = data.tap_to_launch_game.enable ? 'tap' : 'adb'
    return data
  }

  async function load_config() {
    const { data } = await axios.get(`${import.meta.env.VITE_HTTP_URL}/conf`)
    conf.value = parse_config(data)
  }

  function build_config() {
    const data = deepcopy(conf.value)

    for (const i of int2bool) {
      data[i] = data[i] ? 1 : 0
    }
    for (const i of str2list) {
      data[i] = data[i].join(',')
    }
    data.package_type = data.package_type == 'official' ? 1 : 0
    data.resting_threshold = data.resting_threshold / 100
    data.tap_to_launch_game.enable = data.tap_to_launch_game.enable == 'tap'

    return data
  }

  const timestamp = ref(0)
  const post_conf = ref(false)

  watch(
    conf,
    () => {
      if (!post_conf.value) {
        post_conf.value = true
        return
      }
      timestamp.value = Date.now()
      axios.post(`${import.meta.env.VITE_HTTP_URL}/conf`, {
        time: timestamp.value,
        data: build_config()
      })
    },
    { deep: true }
  )

  return {
    load_config,
    load_shop,
    parse_config,
    shop_list,
    timestamp,
    post_conf,
    conf
  }
})
