<?php class pdbdeposition extends baseobject {
	
	protected static array $fields=array(
			'name'=>validator::REQUIRED,
			'rawdatadoi'=>validator::ANY
	);

	protected static array $helpTexts=array(
			'name'=>'The PDB code',
			'rawdatadoi'=>'A DOI or other location for the raw data'
	);

	/**
	 * @param int $id
	 * @param array $request
	 * @return array|null
	 * @throws BadRequestException
	 * @throws NotFoundException
	 * @throws ServerException
	 */
	public static function getcrystals(int $id, array $request=[]): ?array {
	    if(!static::getById($id)){
	        throw new NotFoundException('That PDB does not exist, or you do not have permission to see it');
	    }
	    return database::queryGetAll(
	        'SELECT j.id AS pdbdepositioncrystalid, c.*, di.imagingsessionid AS imagingsessionid, 
                    w.row, w.col, d.dropnumber, p.name AS platename, p.id AS plateid
                FROM project, crystal AS c, welldrop AS d, platewell AS w, plate AS p,
                     pdbdepositioncrystal AS j, dropimage AS di
                WHERE j.pdbdepositionid=:id AND j.crystalid=c.id AND d.id=c.welldropid 
                    AND w.id=d.platewellid AND p.id=w.plateid AND project.id=c.projectid AND di.id=c.dropimageid '
                .database::getFilterClause($request)
                .database::getProjectClause('read')
                .database::getOrderClause($request,'crystal')
                .database::getLimitClause($request),
            array(':id'=>$id)
        );
    }

    /*
     * Returns the PDB entry. Lower-case PDB codes are preferred, so we enforce that here.
     */
    public static function getByName(string $name): ?array {
        return parent::getByName(strtolower($name));
    }

    public static function getByProperty(string $key, string $value, array $request=[]): ?array {
        if('name'==$key){ $value=strtolower($value); }
        return parent::getByProperty($key, $value, $request);
    }

    public static function getByProperties(array $keyValuePairs, array $request=[]): ?array {
        if(isset($keyValuePairs['name'])){
            $keyValuePairs['name']=strtolower($keyValuePairs['name']);
        }
        return parent::getByProperties($keyValuePairs, $request);
    }

    /*
     * Creates the PDB entry. Lower-case PDB codes are preferred, so we enforce that here.
     */
    public static function create(array $request=[]): array {
	    $request['name']=strtolower($request['name']);
        return parent::create($request);
    }

    public static function canCreate(): bool {
        return true;
    }

}