<?php class MXLIMSShipment extends Device {

    const USERNAME='mxlims';
    const USERFULLNAME='MXLIMS Shipment';

	/**
	 * @throws ServerException
	 * @throws BadRequestException
	 * @throws NotFoundException
	 */
	public static function getRandomShipment(): array {
		$shipment=database::queryGetOne('SELECT id FROM shipment WHERE manifest IS NOT NULL ORDER BY RAND() LIMIT 1');
		if(!$shipment) { throw new NotFoundException('Shipment not found'); }
		return MXLIMSShipment::getShipmentByIceBearId($shipment['id']);
	}

	/**
	 * @throws ServerException
	 * @throws NotFoundException
	 * @throws BadRequestException
	 */
	public static function getShipmentByIceBearId(int $shipmentId): array {
		$shipment=shipment::getById($shipmentId);
		if(!$shipment) { throw new NotFoundException('Shipment not found'); }
		return MXLIMSShipment::encodeShipment($shipment);
	}

	/**
	 * @param array $shipment
	 * @return array
	 * @throws BadRequestException
	 * @throws NotFoundException
	 * @throws ServerException
	 */
	private static function encodeShipment(array $shipment): array {
		if(!$shipment['manifest']) { throw new NotFoundException('Shipment has no manifest, cannot encode'); }
		$manifest=json_decode($shipment['manifest']);
		if(!$manifest){ throw new ServerException('Bad manifest, could not encode'); }
		if(isset($manifest['rows'])) {
			$manifest=$manifest['rows'];
		}
		$ret=[];
		$ret["Shipment"]=[];
		$ret['Dewar']=[];
		$ret['Puck']=[];
		$user=user::getById($shipment['shipper']);
		$personUuid=baseuser::getUuid($user['id']);
		$ret['Person'][$personUuid]=[
			'name'=>$user["fullname"],
			'email'=>$user["email"]
		];
		$shipmentUuid=shipment::getUuid($shipment['id']);
		$ret['Shipment'][$shipmentUuid]=[
			'proposalCode'=>$shipment['proposalname'],
			'sessionNumber'=>$shipment['sessionname'],
			'comments'=>'IceBear MXLIMS test',
			'labContactOutbound'=>['$ref'=>'#/Person/'.$personUuid],
			'labContactReturn'=>['$ref'=>'#/Person/'.$personUuid],
			'identifiers'=>[
				'oulu.icebox.icebear.fi'=>(int)$shipment['id']
			],
			'version'=>'0.6.1',
			'mxlimsType'=>'Shipment',
			'mxlimsBaseType'=>'LogisticalSample',
			'uuid'=>$shipmentUuid
		];
		foreach($manifest as $dewar){
			$ret['Dewar'][]=[
				'mxlimsType'=>'Dewar',
				'barcode'=>$dewar['name']
			];
			foreach ($dewar['childitems'] as $puck){
				if(!isset($puck['name'])) { continue; }
			}
		}
		return $ret;
	}

}
