<?php

namespace Roundcube\Tests\Browser\Mail;

use Roundcube\Tests\Browser\Bootstrap;
use Roundcube\Tests\Browser\Components\App;
use Roundcube\Tests\Browser\Components\Popupmenu;
use Roundcube\Tests\Browser\TestCase;

class OpenTest extends TestCase
{
    #[\Override]
    public static function setUpBeforeClass(): void
    {
        Bootstrap::init_imap(true);
        Bootstrap::purge_mailbox('INBOX');

        // import email messages
        foreach (glob(TESTS_DIR . 'data/mail/list_00.eml') as $f) {
            Bootstrap::import_message($f, 'INBOX');
        }
    }

    /**
     * Test Open in New Window action
     */
    public function testOpenInNewWindow()
    {
        $this->browse(function ($browser) {
            if ($browser->isPhone()) {
                $this->markTestSkipped();
            }

            $browser->go('mail');

            $browser->waitFor('#messagelist tbody tr:first-child')
                ->ctrlClick('#messagelist tbody tr:first-child');

            $browser->clickToolbarMenuItem('more');

            $browser->with(new Popupmenu('message-menu'), function ($browser) {
                $uids = $browser->driver->executeScript('return rcmail.message_list.get_selection()');

                $this->assertCount(1, $uids);
                $this->assertTrue(is_int($uids[0]) && $uids[0] > 0);

                $uid = $uids[0];

                [$current_window, $new_window] = $browser->openWindow(static function ($browser) {
                    $browser->clickMenuItem('extwin');
                });

                $browser->driver->switchTo()->window($new_window);

                $browser->with(new App(), static function ($browser) use ($uid) {
                    $browser->assertEnv([
                        'task' => 'mail',
                        'action' => 'show',
                        'uid' => $uid,
                    ]);

                    // TODO: verify the toolbar, which is different here than in the preview frame
                });

                $browser->driver->close();
                $browser->driver->switchTo()->window($current_window);
            });
        });
    }
}
