<?php

namespace Fitsmart\PaypalParcels\ExternalService;

use Fitsmart\PaypalParcels\Contract\TrackingNoteParserInterface;

class TrackingNoteParser implements TrackingNoteParserInterface
{
    public function parse(string $note, array $dataSets): bool|array
    {
        //        TODO: throw an Exception in case of new carrier
        foreach ($dataSets as $dataSet) {
            if (preg_match($dataSet['tracking_number_pattern'], $note, $matchesNumber)) {
                $trackingNumber = $matchesNumber[1];

                if (preg_match($dataSet['tracking_url_pattern'], $note, $matchesUrl)) {
                    $trackingUrl = $matchesUrl[1];
                }
                return [
                    'tracking_number' => $trackingNumber,
                    'tracking_url' => $trackingUrl ?? '',
                    'paypal_carrier' => $dataSet['paypal_carrier'] ?? '',
                    'parcelpanel_carrier' => $dataSet['parcelpanel_carrier'] ?? '',
                    'paypal_carrier_name_other' => $dataSet['paypal_carrier_name_other'] ?? '',
                ];
            }
        }
        return false;
    }
}
