<template>
  <n-divider title-placement="left">
    网络配置
  </n-divider>
  <n-card title=" ">
    <template #header-extra>
      <n-button @click="onRefreshClick">
        <n-icon>
          <RefreshFilled />
        </n-icon>
      </n-button>
    </template>

    <n-data-table
      striped
      :columns="columns"
      :data="networks"
      :max-height="235"
    />
  </n-card>
</template>

<script setup lang="ts">
import { h, ref } from 'vue'
import { NDivider, NCard, NDataTable, NInput, NButton, NIcon, useMessage } from 'naive-ui'
import { Wifi1BarFilled, Wifi2BarFilled, WifiFilled, RefreshFilled } from '@vicons/material'
import { hasIpcRenderer } from '@/utils'

const emit = defineEmits(['done'])

const message = useMessage()
const columns = [
  {
    title: '名称',
    key: 'ssid',
    width: 200,
    ellipsis: true
  },
  {
    title: '信号',
    key: 'signal_level',
    render (row) {
      return h(
        NIcon,
        {
          size: 24,
        },
        {
          default: () => h(
            row.signal_level > -60 ? WifiFilled : row.signal_level > -70 ? Wifi2BarFilled : Wifi1BarFilled
          )
        }
      )
    }
  },
  {
    title: '密码',
    key: 'password',
    width: 200,
    render (row) {
      return h(
        NInput,
        {
          type: 'password',
          onUpdateValue: ($event) => row.password = $event
        }
      )
    }
  },
  {
    title: '操作',
    key: 'actions',
    render (row) {
      return h(
        NButton,
        {
          type: 'info',
          secondary: true,
          disabled: row.ssid === current.value?.ssid || !row.password,
          onClick: () => connect({ ssid:row.ssid, password: row.password })
        },
        { default: () => row.ssid === current.value?.ssid ? '已连接' : '连　接' }
      )
    }
  }
]

const connect = ( connectionOpts ) => {
  if (!connectionOpts.password) {
    message.error('密码为空')
    return
  }
  
  if (!hasIpcRenderer()) return
  
  const result = window.ipcRenderer.sendSync('NETWORK_CONNECT', connectionOpts)
  if (result === 'OK') {
    message.success('网络连接成功')
    emit('done')
  } else {
    message.error(result.message)
  }
}

const current  = ref(undefined)
const networks = ref(undefined)
const init  = () => {
  if (!hasIpcRenderer()) return

  const result   = window.ipcRenderer.sendSync('NETWORK_QUERY')
  if (!result.networks) return
  
  current.value  = result.current[0]
  networks.value = result.networks
}
const reset = () => {
  current.value  = undefined
  networks.value = undefined
}

const onRefreshClick = () => {
  if (!hasIpcRenderer()) return

  window.ipcRenderer.sendSync('NETWORK_DISCONNECT')

  setTimeout(() => {
    reset()
    init()
  }, 500)
}

defineExpose({ init, reset })
</script>

<style scoped lang="less">
.n-table {
  text-align: center;
}
</style>