<?php class imagerloadlog extends baseobject { 
	
	protected static array $fields=array(
		'name'=>validator::REQUIRED,
		'imagerid'=>array(validator::REQUIRED, validator::INTEGER),
		'loadingdate'=>array(validator::REQUIRED, validator::DATE),
		'platesactive'=>array(validator::REQUIRED, validator::INTEGER),
		'platesexpired'=>array(validator::REQUIRED, validator::INTEGER),
	);
	
	protected static array $helpTexts=array(
		'name'=>'A unique name for the log entry in the form imagerNNNNNN_YYYY-MM-DD',
		'imagerid'=>'The imager',
		'loadingdate'=>'The date of this imager loading record',
		'platesactive'=>'How many plates in the imager have inspections scheduled',
		'platesexpired'=>'How many plates in the imager have no inspections scheduled',
	);

	/**
	 * @param array $request
	 * @return array
	 * @throws BadRequestException
	 */
	public static function create(array $request=[]): array {
		throw new BadRequestException('Create not implemented on imagerloadlog. Call log() instead.');
	}

	/**
	 * @param int $id
	 * @param array $request
	 * @return array
	 * @throws BadRequestException
	 */
	public static function update(int $id, array $request=[]): array {
		throw new BadRequestException('Update not implemented on imagerloadlog. Call log() instead.');
	}

    /**
     * @param array $request
     * @return array
     * @throws BadRequestException
     * @throws ForbiddenException
     * @throws NotFoundException
     * @throws ServerException
     */
	public static function log(array $request=[]): array {
		foreach(static::$fields as $k=>$v){
			if('name'==$k){ continue; }
			//just check they all exist. Full validation is done in parent create or update.
			if(!isset($request[$k])){
				throw new BadRequestException('Field '.$k.' is required in imagerloadlog::log()');
			}
		}
		$imagerId=$request['imagerid'];
		$date=$request['loadingdate'];
		$logName='imager'.$imagerId.'_'.$date;
		$existing=static::getByName($logName);
		$request['_classname']='imagerloadlog';
		if($existing){
			return parent::update($existing['id'], $request);
		} else {
			$request['name']=$logName;
			return parent::create($request);
		}
	}
	
}