<?php

namespace App\Console\Commands\Mock;

use App\Packages\Friend\Models\FriendRelation;
use App\Packages\User\Models\User;
use Illuminate\Console\Command;

class MockFriendCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mock:friend';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create users mock friends';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $users = User::repository()->getRegisteredUsers();

        if (!$users) {
            $this->info('No registered users');

            return false;
        }

        $maxFriends = (int)$this->ask('Max friends per user') ?: 10;

        $statusBar = $this->output->createProgressBar($users->count());
        $statusBar->start();

        foreach ($users as $user) {

            for ($i = 0; $i <= rand(0, $maxFriends); $i++) {
                $exit = 0;
                $finded = false;
                do {
                    $random_user = $users->random();
                    if (!FriendRelation::repository()->existsFriend($user, $random_user)) {
                        $finded = true;
                    }
                    $exit++;
                } while (!$finded && $exit <= 5);

                FriendRelation::createFriend($user, $random_user);
            }

            $statusBar->advance();
        }

        $statusBar->finish();
        $this->info('');
    }
}
