<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Http;

class Device extends BaseModel
{
    public static function boot(): void
    {
        parent::boot();
        static::creating(function (Device $device) {
            $device->user_uuid = auth()->check() ? auth()->id() : null;
        });
        static::updating(function (Device $device) {
            $device->user_uuid = auth()->check() ? auth()->id() : null;
        });
    }

    public function Registers(): HasMany
    {
        return $this->hasMany(Register::class, 'device_uuid', 'uuid');
    }

    public function Children(): HasMany
    {
        return $this->hasMany(self::class, 'parent_uuid', 'uuid');
    }

    public function Parent(): BelongsTo
    {
        return $this->belongsTo(self::class, 'parent_uuid', 'uuid');
    }

    public function Patterns(): HasMany
    {
        return $this->hasMany(Pattern::class, 'device_uuid', 'uuid');
    }

    public function SendToClient(): void
    {
        $response = Http::post(env('API_URL') . 'devices', [
            'name' => $this->name,
            'topic' => $this->mqtt_topic,
            'token' => env('API_TOKEN'),
            'description' => $this->description,
        ]);
        $data = $response->json()['data'];
        $this->server_id = $data['id'];
        $this->save();
//        foreach ($this->Registers as $register) {
//            Http::post(env('API_URL') . 'registers', [
//                'key' => $register->key,
//                'type' => $register->type,
//                'device_uuid' => $data['id'],
//                'title' => $register->title,
//                'value' => $register->value,
//                'token' => env('API_TOKEN'),
//            ]);
//        }
    }

    public function UpdateRegisters(): void
    {
        $response = Http::get(env('API_URL') . 'registers', [
            'device_uuid' => $this->server_id,
            'token' => env('API_TOKEN'),
        ]);
        $registers = $response->json()['data'];
        foreach ($registers as $register) {
            Register::where('device_uuid', $this->uuid)->where('key', $register['key'])->first()->update([
                'value' => $register['value'],
            ]);
        }
    }

    public function Translate(): void
    {
        TranslateAll($this, ['name', 'brand', 'model', 'description']);
        $this->Registers->map(function ($register) {
            $register->Translate();
        });
    }
}
