<?php

class Tracking_HelenaExpress {

    /**
     *
     * @global type $SETTINGS
     * @param string $code
     * @return \TrackingInfo
     * @throws TrackingException
     */
    public static function track(string $code): TrackingInfo {
        global $SETTINGS;

        $barcode = new TrackingBarcode($code);

        try {
            $status = json_decode(file_get_contents("https://apis.helena.express/v1/track/?code=" . $barcode->getCode()));
        } catch (Exception $ex) {
            throw new TrackingException("There was a server problem. This code cannot be tracked right now.");
        }

        if (empty($status->events) && empty($status->info->carrier)) {
            throw new TrackingException("Unknown tracking code (best guess: " . Carriers::getCarrierName($barcode->getCarrier()) . ").");
        }

        $info = new TrackingInfo();

        $info->setCode($barcode->getCode());
        $info->setCarrier($status->info->carrier);
        $info->setService(new Service("", "Local Courier"));
        $info->setCarrierAttributionText(CarrierAssets::getAttribution(Carriers::getCarrierCode($info->getCarrier())));
        $info->setCarrierLogo(CarrierAssets::getLogo(Carriers::getCarrierCode($info->getCarrier())));

        if (!empty($status->events)) {
            $current_status = new TrackingEntry(
                    TrackingStatus::stringToStatus($status->events[0]->eventtype),
                    $status->events[0]->text,
                    $status->events[0]->timestamp
            );

            $info->setCurrentStatus($current_status);
        }


        foreach ($status->events as $event) {
            $info->appendHistoryEntry(new TrackingEntry(TrackingStatus::stringToStatus($event->eventtype), $event->text, $event->timestamp));
        }

        return $info;
    }

}
