<?php class audiorecording extends baseobject {

    protected static array $fields=array(
        'name'=>validator::REQUIRED,
        'userid'=>validator::ANY, //required, but pulled from session
        'parentid'=>array(validator::REQUIRED, validator::INTEGER),
        'datetime'=>array(validator::REQUIRED, validator::DATETIME),
        'audiodata'=>validator::ANY //required, but code will validate
    );
    protected static array $helpTexts=array();

    protected static string $adminSelect='SELECT audiorecording.*, user.fullname AS userfullname FROM audiorecording, user, project 
                WHERE audiorecording.userid=user.id AND audiorecording.projectid=project.id ';
    protected static string $normalSelect='SELECT audiorecording.*, user.fullname AS userfullname FROM audiorecording, user, project 
                WHERE audiorecording.userid=user.id AND audiorecording.projectid=project.id ';

    public static function create(array $request=[]): array {
        if(!isset($_FILES['audiodata'])){
            throw new BadRequestException("No audio data file");
        }
        if(!isset($request['name'])){
            $request['name']='user'.session::getUserId().'_'.date('Y-m-d H:i:s');
        }
        $request['datetime']=date('Y-m-d H:i:s');
        $request['userid']=session::getUserId();
        $parent=baseobject::getById($request['parentid']);
        if(!$parent){
            throw new NotFoundException('Either the parent object does not exist, or you cannot see it');
        }
        $projectId=$parent['projectid'];
        if(!static::canCreateRecordingsInProject($projectId)){
            throw new ForbiddenException('You cannot record audio in the parent object\'s project.');
        }
        $request['projectid']=$projectId;
        $ret=parent::create(array(
            'parentid'=>$request['parentid'],
            'projectid'=>$request['projectid'],
            'datetime'=>$request['datetime'],
            'userid'=>$request['userid'],
            'name'=>$request['name']
        ));
        $id=$ret['created']['id'];
        $fileStorePath=rtrim(trim(config::get('core_filestore'),'/'));
        $fileBackupPath=rtrim(trim(config::get('core_filestorebackup'),'/'));
        $recordingsDirectory='/files/project'.$projectId.'/audio/';


        if(!@move_uploaded_file($_FILES['audiodata']['tmp_name'],$fileStorePath.$recordingsDirectory.'recording'.$id)){
            throw new ServerException('Could not save audio file');
        }
        if(""!=$fileBackupPath && @copy($fileStorePath.$recordingsDirectory.'recording'.$id, $fileBackupPath.$recordingsDirectory.'recording'.$id)){
            throw new ServerException('Could not save audio file to backup storage');
        }

        return $ret;
    }

	/**
	 * @param int $projectId
	 * @return bool
	 * @throws BadRequestException
	 * @throws NotFoundException
	 * @throws ServerException
	 */
    public static function canCreateRecordingsInProject(int $projectId): bool {
        if (session::isAdmin() || session::isShipper()){ return true; }
        return in_array($projectId, session::getCreateProjects());
    }

	/**
	 * @param int $parentId
	 * @throws BadRequestException
	 * @throws ServerException
	 */
    public static function setProjectIdsToMatchParent(int $parentId): void {
        $parent=baseobject::getById($parentId);
        if(!$parent){ throw new ServerException('Attempted to set project IDs on audio recordings for object with ID '.$parentId.' but it does not exist'); }
        $projectId=$parent['projectid'];
        $stmt='UPDATE audiorecording set projectid=:projectid WHERE parentid=:parentid';
        database::query($stmt,array(':projectid'=>$projectId, ':parentid'=>$parentId));
    }


}