<?php

namespace App\Filament\Widgets;

use App\Services\EtcdService;
use Filament\Notifications\Notification;
use Filament\Widgets\Widget;
use Illuminate\Support\Facades\DB;

class UpdateConfigWidget extends Widget
{
    protected static string $view = 'filament.widgets.update-config-widget';

    public function updateSettingsToEtcd()
    {
        try {
            $etcd = new EtcdService();
//            $etcd->deleteByPrefix("datasource");

            $settings = DB::table('settings')
                ->where('group', 'datasource')
                ->get(); // 获取 group 为 datasource 的所有记录

            foreach ($settings as $setting) {
                $key = '/' . $setting->group . '/' . $setting->name;
                $etcd->put($key, $setting->payload);
            }

            $metrics = DB::table('metrics')->get(); // 获取所有 metrics 数据

            foreach ($metrics as $index => $metric) {
                $baseKey = '/metrics/' . $index;

                // 存储 name 到 etcd
                $etcd->put($baseKey . '/name', $metric->name);

                // 存储 identifier_type 到 etcd
                $etcd->put($baseKey . '/identifier_type', $metric->identifier_type);

                // 根据 identifier_type 生成 nodeid 并存储到 etcd
                switch ($metric->identifier_type) {
                    case 1: // Numeric
                        $nodeId = 'ns=' . $metric->namespace_index . ';i=' . $metric->numeric_id;
                        break;
                    case 2: // String
                        $nodeId = 'ns=' . $metric->namespace_index . ';s=' . $metric->string_id;
                        break;
                    case 3: // GUID
                        $nodeId = 'ns=' . $metric->namespace_index . ';g=' . $metric->guid_id;
                        break;
                    default:
                        $nodeId = ''; // 若 identifier_type 不符合预期，则 nodeId 为空
                        break;
                }
                $etcd->put($baseKey . '/nodeid', $nodeId);

                // 存储 help 到 etcd
                $etcd->put($baseKey . '/help', $metric->help ?? '');
            }

            Notification::make()
                ->title('配置更新成功！')
                ->success() // 设置为成功类型
                ->send(); // 发送通知

        } catch (\Exception $e) {
            // 失败通知
            Notification::make()
                ->title('配置更新失败！')
                ->danger() // 设置为错误类型
                ->body($e->getMessage()) // 显示异常信息
                ->send(); // 发送通知
        }
    }
}
