<?php

namespace App\Livewire\Frontend;

use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use App\Models\ZEmail;
use Livewire\Component;

class Email extends Component
{
    public $list = false;

    public $type;

    public $email;

    public $emails;

    public $initial;

    protected $listeners = ['updateEmail' => 'syncEmail', 'getEmail' => 'generateEmail'];

    public function mount(): void
    {
        $this->email = ZEmail::getEmail();
        $this->emails = ZEmail::getEmails();
        $this->initial = false;
        $this->checkMultipleEmails();
    }

    private function checkMultipleEmails(): void
    {
        if (count($this->emails) === 0) {
            $this->emails = [$this->email];
        }
        $this->list = count($this->emails) > 1;
    }

    public function switchEmail($email): Redirector|RedirectResponse
    {
        return to_route('switch', ['email' => $email]);
    }

    public function syncEmail(): void
    {
        $this->email = ZEmail::getEmail();
        $this->emails = ZEmail::getEmails();
        if (count($this->emails) === 0) {
            $this->dispatch('getEmail');
        }
        $this->checkMultipleEmails();
        $this->dispatch('syncMailbox', $this->email);
        $this->dispatch('fetchMessages');
    }

    public function generateEmail(): void
    {
        if ($this->email == null) {
            ZEmail::generateRandomEmail();
        }
        $this->checkMultipleEmails();
        $this->dispatch('updateEmail');
    }

    public function render()
    {
        return view('livewire.frontend.email')->with(['email' => $this->email, 'emails' => $this->emails, 'initial' => $this->initial, 'type' => $this->type, 'list' => $this->list]);
    }
}
