<?php class crystalscoringsystem extends baseobject {
	
	protected static array $fields=array(
			'name'=>validator::REQUIRED,
			'iscurrent'=>validator::BOOLEAN,
	);
	
	protected static array $helpTexts=array(
			'name'=>'A unique name for this scoring system',
			'iscurrent'=>'Whether this system should be used for new plates',
	);

    /**
     * @param array $request
     * @return array
     * @throws BadRequestException
     * @throws NotFoundException if the Shared project is not found
     * @throws ForbiddenException
     * @throws ServerException
     */
	public static function create(array $request=array()): array {
		$request['projectid']=project::getSharedProjectId();
		return parent::createByClassName($request,'crystalscoringsystem');
	}

	/**
	 * @throws BadRequestException
	 * @throws ServerException
	 */
	public static function canCreate(): bool {
		return project::canCreateInProject(project::getSharedProjectId());
	}

	/**
	 * @param int $id
	 * @param array $request
	 * @return array|null
	 * @throws BadRequestException
	 * @throws ServerException
	 */
	public static function getscores(int $id, array $request=[]): ?array {
		return crystalscore::getByProperty('crystalscoringsystemid',$id, $request);
	}

	/**
	 * Returns the crystalscore in this system that best matches the supplied name, or null. Case-insensitive.
	 * First looks for an exact match of $name, then for a score beginning with $name, then for one containing $name, then returns null.
	 * @param int $id
	 * @param string $name
	 * @return array|null
	 * @throws BadRequestException
	 * @throws ServerException
	 */
    public static function getScoreBestMatchingName(int $id, string $name): ?array {
        $name=strtolower($name);
        $scores=static::getscores($id);
        if(!$scores){ return null; }
        foreach ($scores['rows'] as $score) {
            if (strtolower($score['label'])==$name){
                return $score;
            }
        }
        foreach ($scores['rows'] as $score) {
            if (stripos($score['label'],$name)===0){
                return $score;
            }
        }
        foreach ($scores['rows'] as $score) {
            if (stripos($score['label'],$name)!==false){
                return $score;
            }
        }
		return  null;
    }

}
