<?php

class Tracking_UPS_MailInnovations_DataMatrix {

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

        $info = new TrackingInfo();

        if (empty($codeparts[13])) {
            $from = new Location();
            $from->city = "Unknown";

            $to = new Location();
            $to->street = implode(" ", [$codeparts[4], $codeparts[5]]);
            $to->city = $codeparts[6];
            $to->state = $codeparts[7];
            $to->zip = $codeparts[8];
            $to->country = (new League\ISO3166\ISO3166)->numeric($codeparts[9])['alpha2'];

            $info->setCode($to->zip);
            $info->setTo($to);
            $info->setFrom($from);
            $info->setCarrier("usps");
            $info->setService(new Service("", "UPS Mail Innovations"));
            $info->setCurrentStatus(new TrackingEntry(TrackingStatus::TRACKING_STATUS_UNKNOWN, "Item is an untracked flat or international mailpiece.", time(), new Location()));
        } else {
            $realcode = $codeparts[13];

            $info = Tracking::track($realcode, "usps");

            // Set detailed destination address from code data
            $to = $info->getTo();
            if (is_null($to)) {
                $to = new Location();
            }
            $to->street = implode(" ", [$codeparts[4], $codeparts[5]]);
            $to->city = $codeparts[6];
            $to->state = $codeparts[7];
            $to->zip = $codeparts[8];
            $to->country = (new League\ISO3166\ISO3166)->numeric($codeparts[9])['alpha2'];
            $info->setTo($to);

            $info->setService(new Service("", "Parcel Select/UPS Mail Innovations"));
        }

        return $info;
    }

}
