<?php

namespace App\Teamtable;

use \InvalidArgumentException;

/**
 * Represents a record in the teamtable
 */
class Team
{
    public int    $id;
    public string $name         = 'NN';
    public string $company      = 'NN';
    public string $cardnumber   = 'NN';
    public string $leader       = 'NN';
    public string $phone        = 'NN';
    public int    $participants = 0;
    public int    $rounds       = 0;
    public ?int   $best_time    = NULL;

    /**
     * PHP by default does not include multi byte functions. Therefore we use this
     */
    private function count_characters(string $string): int
    {
        return count(preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY));
    }

    /**
     * Check if string is longer than length
     */
    private function longerThan(string $string, int $length): bool 
    {
        if ($this->count_characters($string) > $length)
        {
           return TRUE; 
        }
        return FALSE;
    }

    public function setName(string $name): Self
    {
        if ($this->longerThan($name, 32))
        {
            throw new InvalidArgumentException("Name is too long!");
        }
        $this->name = $name;
        return $this;
    }

    public function setCompany(string $company): Self
    {
        if ($this->longerThan($company, 32))
        {
            throw new InvalidArgumentException("Company is too long!");
        }
        $this->company = $company;
        return $this;
    }

    public function setCardnumber(string $cardnumber): Self
    {
        if ($this->longerThan($cardnumber, 32))
        {
            throw new InvalidArgumentException("Cardnumber is too long!");
        }
        $this->cardnumber = $cardnumber;
        return $this;
    }

    public function setLeader(string $leader): Self
    {
        if ($this->longerThan($leader, 32))
        {
            throw new InvalidArgumentException("Leader is too long!");
        }
        $this->leader = $leader;
        return $this;
    }

    public function setPhone(string $phone): Self
    {
        if ($this->longerThan($phone, 20))
        {
            throw new InvalidArgumentException("Phone number is too long!");
        }
        $this->phone = $phone;
        return $this;
    }

    public function setParticipants(int $participants): Self
    {
        if ($participants > 9999)
        {
            throw new InvalidArgumentException("Too many participants!");
        }
        $this->participants = $participants;
        return $this;
    }

    public function setRounds(int $rounds): Self
    {
        if ($rounds > 9999)
        {
            throw new InvalidArgumentException("Too many rounds!");
        }
        $this->rounds = $rounds;
        return $this;
    }
}