<?php class protein extends baseobject {
	
	protected static array $fields=array(
			'name'=>validator::REQUIRED,
			'description'=>validator::REQUIRED,
            'proteinacronym'=>validator::ANY
	);
	
	protected static array $helpTexts=array(
			'name'=>'A unique name for this protein',
			'proteinacronym'=>'Short code, 3-5 characters. Identifies the protein for synchrotron safety purposes',
			'description'=>'Short description of this protein',
	);
	
	public static string $defaultSortOrder='name ASC';

	/**
	 * Whether the user has permission to create a protein in at least one project. As currently implemented, this
	 * should be administrators, technicians and project owners.
	 * @return bool true if this user can create proteins, otherwise false.
	 * @throws BadRequestException
	 * @throws NotFoundException if the Technicians usergroup does not exist.
	 * @throws ServerException
	 */
	public static function canCreate(): bool {
		if(session::isAdmin()){ return true; }
		$grp=usergroup::getByName(usergroup::TECHNICIANS);
		if(usergroup::userisingroup($grp['id'])) return true;
		$userId=session::getUserId();
		$projects=session::getCreateProjects(true);
		foreach($projects['rows'] as $p){
			if($p['owner']==$userId){ return true; }
		}
		return false;
	}

    /**
     * Creates a protein.
     * @param array $request
     * @return array
     * @throws BadRequestException
     * @throws ForbiddenException
     * @throws NotFoundException
     * @throws ServerException
     */
	public static function create(array $request=[]): array {
		if(!session::isAdmin()){
			$project=project::getById($request['projectid']);
			if(!$project){
				throw new NotFoundException('Project does not exist, or you do not have permission to see it');
			}
			if($project['owner']!=session::getUserId()){
				throw new ForbiddenException('You must own the project to create proteins and constructs in it');
			}
		}
		$result=parent::create($request);
		if(isset($result['created'])){
			//Create a "Full Length" construct with sequence(s) 
			$request['name']='Full length';
			$request['description']='The full sequence';
			$request['proteinid']=$result['created']['id'];
			construct::create($request); 
		}
		return $result;
	}

    /**
     * Gets the constructs for this protein.
     * @param int $id The protein ID
     * @param array $request Request parameters such as pagination
     * @return array
     * @throws BadRequestException
	 * @throws ServerException
     * @noinspection PhpUnused
     */
	public static function getconstructs(int $id, array $request=[]): array {
		return construct::getByProperty('proteinid',$id,$request);
	}

}