<template>
  <div class="columns is-centered mx-0">
    <div class="column is-6">
    <article class="message is-danger">
  <div class="message-header">
    <p class="fsb-20 has-text-white">{{$lang('warning')}}</p>
  </div>
  <div class="message-body has-text-black fs-17">
    {{$lang('alert')}}
  </div>
</article>
<div class="field is-horizontal">
  <div class="field-body">
  <div class="field is-narrow">
  <label class="label">{{ $lang('confirm') }} <b class="has-text-danger">*</b></label>
  <div class="control">
    <input class="input" type="text" :placeholder="$lang('info')" v-model="text">
  </div>
  <p class="help has-text-danger" v-if="errors.text">{{ errors.text }}</p>
</div>
  <div class="field">
  <label class="label">{{ $lang('hash') }} <b class="has-text-danger">*</b></label>
  <div class="control">
    <input class="input" type="text" placeholder="secret key" v-model="password">
  </div>
  <p class="help has-text-danger" v-if="errors.password">{{ errors.password }}</p>
</div>
</div>
</div>
<div class="mt-5">
  <button :class="`button is-danger ${loading? 'is-loading' : ''} has-text-white`" @click="deletion()">
    Xóa dữ liệu
  </button>
  </div>
  </div>
  </div>
</template>
<script setup>
  const { $empty, $insertapi, $snackbar, $lang } = useNuxtApp()
  var text = ref()
  var password = ref()
  var hash = ref()
  var loading = ref(false)
  var errors = ref({})
  async function sha256(str) {
    const buffer = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(str));
    return Array.from(new Uint8Array(buffer)).map(b => b.toString(16).padStart(2, '0')).join('');
  }
  async function checkError() {
    errors.value = {}
    if(text.value!=='delete') errors.value.text = "Chưa nhập xác nhận xóa"
    if($empty(password.value)) errors.value.password = "Chưa nhập chuỗi bí mật"
    else {
      hash.value = await sha256(password.value)
      if(hash.value !=='8816f9082eb2a9adf08dca6e0273d40908f409b6f8ca60bbeedd5d8d437c603b') {
        errors.value.password = "Chuỗi bí mật không chính xác"
      }
    }
    return Object.keys(errors.value).length>0
  }
  async function deletion() {
    let rs = await checkError()
    if(rs) return
    loading.value = true
    rs = await $insertapi('datadeletion', {password: password.value, hash: hash.value})
    if(rs==='error') $snackbar($lang('delete-error'))
    else $snackbar($lang('delete-success'))
    text.value = undefined
    password.value = undefined
    loading.value = false
  }
</script>