<?php class shipmentdestination extends baseobject { 
	
	protected static array $fields=array(
		'name'=>validator::REQUIRED,
        'ismanaged'=>validator::BOOLEAN,
        'isavailable'=>validator::BOOLEAN,
        'ishome'=>validator::BOOLEAN,
	    'shipmenthandler'=>validator::ANY,
        'apibaseuri'=>validator::ANY,
        'clientbaseuri'=>validator::ANY,
        'geofence'=>validator::GEOFENCE
	);
	
	protected static array $helpTexts=array(
		'name'=>'The name of the shipment destination',
        'ismanaged'=>'Whether IceBear creates and maintains this synchrotron automatically',
        'isavailable'=>'Whether this synchrotron is available as a destination for shipments in IceBear',
        'ishome'=>'If true, this location is the home lab. Trackers entering/leaving this may trigger special actions.',
	    'shipmenthandler'=>'Name of the Javascript shipment handler object',
        'apibaseuri'=>'Base URI of synchrotron API',
        'clientbaseuri'=>'Base URI of synchrotron client',
        'geofence'=>'Defines an area enclosing the synchrotron, for trackers, etc.'
	);

    /**
     * @param array $request
     * @return array
     * @throws BadRequestException
     * @throws ForbiddenException
     * @throws NotFoundException
     * @throws ServerException
     */
	public static function create(array $request=[]): array {
	    if(!static::canCreate()){ throw new ForbiddenException('You cannot create shipment destinations'); }
	    $request['projectid']=project::getSharedProjectId();
	    $created=parent::createByClassName($request, 'shipmentdestination');
        if(('home'==strtolower($request['name'])) || (isset($request['ishome']) && 1===1*$request['ishome'])){
            shipmentdestination::setHome($created['created']['id']);
        }
        return $created;
	}

    public static function update(int $id, $request=[]): array {
        $updated=parent::update($id, $request);
        if((isset($request['name']) && 'home'==strtolower($request['name'])) || (isset($request['ishome']) && 1===1*$request['ishome'])){
            shipmentdestination::setHome($id);
        }
        return $updated;
    }

    /**
     * @return bool
     * @throws BadRequestException
     * @throws NotFoundException|ServerException
	 */
	public static function canCreate(): bool {
		if(session::isAdmin()){ return true; }
		$grp=usergroup::getByName(usergroup::SHIPPERS);
		if(usergroup::userisingroup($grp['id'])){ return true; }
		$grp=usergroup::getByName(usergroup::TECHNICIANS);
		return usergroup::userisingroup($grp['id']);
	}

	/**
	 * Gets shipments for this shipment destination.
	 * @param int $id The shipment ID.
	 * @param array $request The request parameters, e.g., pagination.
	 * @return array|null
	 * @throws BadRequestException
	 * @throws ServerException
	 */
	public static function getshipments(int $id, array $request=[]): ?array {
	    return shipment::getByProperty('shipmentdestinationid', $id, $request);
	}

    /**
     * Gets beamlines for this shipment destination.
     * @param int $id The shipment ID.
     * @param array $request The request parameters, e.g., pagination.
     * @return array
     * @throws BadRequestException
     * @throws NotFoundException
     * @throws ServerException
     */
	public static function getbeamlines(int $id, array $request=[]): ?array {
        return beamline::getByProperty('shipmentdestinationid', $id, $request);
    }

    /**
     * Returns the names of all the shipment handler Javascript files.
     * @return array
     */
	public static function getHandlerScriptNames(): array {
	    $files=dir(config::getWwwRoot().'/client/js/model/shipping/handlers/');
	    $handlers=array();
	    while (false!==($name=$files->read())) {
	        if('.'==$name || '..'==$name){ continue; }
	        if(str_ends_with($name, 'ShippingHandler.js')){
	            $handlers[]=substr($name, 0, -3);
	        }
	    }
	    $files->close();
	    return $handlers;
	}

    /**
     * Sets the specified destination as the home lab, and unsets all the others.
     * @throws ServerException
     * @throws BadRequestException
     */
    public static function setHome(int $id): void {
        database::query('UPDATE shipmentdestination SET ishome=FALSE WHERE ishome<>FALSE');
        database::query('UPDATE shipmentdestination SET ishome=TRUE WHERE id=:id', array(':id'=>$id));
    }

}