<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Search\Utils;

use libphonenumber\PhoneNumberUtil;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class ExtractPhonenumberFromPattern
{
    private const PATTERN = '([\+]{0,1}[0-9\ ]{5,})';

    private readonly string $defaultCarrierCode;

    public function __construct(ParameterBagInterface $parameterBag)
    {
        $this->defaultCarrierCode = $parameterBag->get('chill_main')['phone_helper']['default_carrier_code'];
    }

    public function extractPhonenumber(string $subject): SearchExtractionResult
    {
        $matches = [];
        \preg_match(self::PATTERN, $subject, $matches);

        if (0 < \count($matches)) {
            $phonenumber = [];
            $length = 0;

            foreach (\str_split(\trim($matches[0])) as $key => $char) {
                switch ($char) {
                    case '+':
                        if (0 === $key) {
                            $phonenumber[] = $char;
                        } else {
                            throw new \LogicException('should not match not alnum character');
                        }

                        break;

                    case '0':
                        $length++;

                        if (0 === $key) {
                            $util = PhoneNumberUtil::getInstance();
                            $phonenumber[] = '+'.$util->getCountryCodeForRegion($this->defaultCarrierCode);
                        } else {
                            $phonenumber[] = $char;
                        }

                        break;

                    case '1':
                    case '2':
                    case '3':
                    case '4':
                    case '5':
                    case '6':
                    case '7':
                    case '8':
                    case '9':
                        $length++;
                        $phonenumber[] = $char;

                        break;

                    case ' ':
                        break;

                    default:
                        throw new \LogicException('should not match not alnum character');
                }
            }

            if (5 < $length) {
                return new SearchExtractionResult($subject, [\implode('', $phonenumber)]);
            }
        }

        return new SearchExtractionResult($subject, []);
    }
}
