<?php

namespace App\Livewire\Frontend;

use App\ColorPicker;
use App\Models\Email;
use App\Models\Message;
use App\Models\ZEmail;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Livewire\Component;

class Mailbox extends Component
{
    use ColorPicker;

    public $messages = [];

    public $deleted = [];

    public $error = '';

    public $email;

    public $initial = false;

    public $type;

    public $overflow = false;

    public $messageId;

    protected $listeners = ['fetchMessages' => 'fetch', 'syncMailbox' => 'syncEmail', 'setMessageId' => 'setMessageId'];

    public function mount()
    {
        $this->email = ZEmail::getEmail();
        $this->initial = false;
        if (! ZEmail::getEmail()) {
            return to_route('home');
        }
        return null;
    }

    public function syncEmail($email): void
    {
        $this->email = $email;
        $this->initial = false;
        $this->messages = [];
    }

    public function fetch(): void
    {
        try {
            $count = count($this->messages);
            if ($count > 0) {
                $this->messages = [];
            }
            $responses = [];
            if (config('app.beta_feature') || ! json_decode((string) config('app.settings.imap_settings'))->cc_check) {
                $responses = [
                    'to' => ZEmail::getMessages($this->email, 'to', $this->deleted),
                    'cc' => [
                        'data' => [],
                        'notifications' => [],
                    ],
                ];
            } else {
                $responses = [
                    'to' => ZEmail::getMessages($this->email, 'to', $this->deleted),
                    'cc' => ZEmail::getMessages($this->email, 'cc', $this->deleted),
                ];
            }

            $this->deleted = [];
            $this->messages = array_merge($responses['to']['data'], $responses['cc']['data']);
            $notifications = array_merge($responses['to']['notifications'], $responses['cc']['notifications']);

            if (count($notifications)) {
                if (! $this->overflow && count($this->messages) === $count) {
                    $this->overflow = true;
                }
            } else {
                $this->overflow = false;
            }

            foreach ($notifications as $notification) {
                $this->dispatch('showNewMailNotification', $notification);
            }
            ZEmail::incrementMessagesStats(count($notifications));
        } catch (Exception $e) {
            if (Auth::check() && Auth::user()->level == 9) {
                $this->error = $e->getMessage();
            } else {
                $this->error = 'Not able to connect to Mail Server';
            }
        }
        $this->dispatch('stopLoader');
        $this->initial = true;
    }

    public function delete(string $messageId): void
    {

        try {
            if (config('app.beta_feature')) {
                Message::query()->find($messageId)->delete();
            }
            if (config('app.fetch_from_db')) {
                Email::query()->where(['message_id' => $messageId])->delete();
            }
            $this->deleted[] = $messageId;
            foreach ($this->messages as $key => $message) {
                if ($message['id'] == $messageId) {
                    $directory = public_path('tmp/attachments/').$messageId;
                    $this->rrmdir($directory);
                    unset($this->messages[$key]);
                }
            }

        } catch (
            Exception $exception
        ) {
            Log::error($exception->getMessage());
        }

    }

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

    private function rrmdir(string $dir): void
    {
        if (is_dir($dir)) {
            $objects = scandir($dir);
            foreach ($objects as $object) {
                if ($object !== '.' && $object !== '..') {
                    if (is_dir($dir.DIRECTORY_SEPARATOR.$object) && ! is_link($dir.'/'.$object)) {
                        $this->rrmdir($dir.DIRECTORY_SEPARATOR.$object);
                    } else {
                        unlink($dir.DIRECTORY_SEPARATOR.$object);
                    }
                }
            }
            rmdir($dir);
        }
    }
}
