U
    Yh"                     @   s   d Z ddlZddlZddlmZ ddlmZ ddlmZm	Z	 ddl
mZmZmZ ddlmZ dd	lmZmZmZ dd
lmZ ddlmZmZ dZdZdZdeeef eeddddZG dd deZ G dd deZ!dS )u  
***************************************************************************
    QGIS Server Plugin Filters: Add a new request to print a specific atlas
    feature
    ---------------------
    Date                 : December 2019
    Copyright            : (C) 2019 by René-Luc D'Hont - 3Liz
    Email                : rldhont at 3liz dot com
***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************
    N)Path)Dict)QgsExpression
QgsProject)QgsServerRequestQgsServerResponse
QgsService)pluginMetadata   )AtlasPrintExceptionparse_output_formatprint_layout)Logger)get_lizmap_groupsget_lizmap_user_loginzCopyright 2021, 3LizzGPL version 3zinfo@3liz.org   )dataresponsecodereturnc                 C   s*   | | |dd |t|  dS )z! Write data as json response
    Content-Typezapplication/jsonN)setStatusCode	setHeaderwritejsondumps)r   r   r    r   4/var/www/lizmap/lizmap/plugins/atlasprint/service.pywrite_json_response&   s    
r   c                       s6   e Zd Zeedd fddZeddddZ  ZS )AtlasPrintErrorN)r   msgr   c                    s0   t  | || _|| _t d|| d S )Nz Atlas print request error {}: {})super__init__r    r   r   criticalformat)selfr   r    	__class__r   r   r"   0   s    zAtlasPrintError.__init__)r   r   c                 C   s&   d| j d}|  t||| j dS )z Format error response
        Zfail)statusmessageN)r    clearr   r   )r%   r   bodyr   r   r   formatResponse6   s    zAtlasPrintError.formatResponse)	__name__
__module____qualname__intstrr"   r   r,   __classcell__r   r   r&   r   r   .   s   r   c                       s   e Zd Zdedd fddZedddZedd	d
Zej	edddZ
eeeddddZeeeef eeddddZeeef eeeeddddZ  ZS )AtlasPrintServiceFN)debugr   c                    s   t    |}t | _d S )N)r!   r"   r   logger)r%   r4   _r&   r   r   r"   @   s    
zAtlasPrintService.__init__)r   c                 C   s   dS )z Service name
        ATLASr   r%   r   r   r   nameG   s    zAtlasPrintService.namec                 C   s   dS )z Service version
        z1.0.0r   r8   r   r   r   versionL   s    zAtlasPrintService.version)methodr   c                 C   s   |t jt jfkS )z& Check supported HTTP methods
        )r   	GetMethod
PostMethod)r%   r;   r   r   r   allowMethodR   s     zAtlasPrintService.allowMethod)requestr   projectr   c              
   C   sn  |  }z&z|dd }|dkr6| ||| n|dkr|	 }t
||}t||}	| }|dd|kr| jd	 ||d< t|	|d< || | |||||	 ntd
d|W nj tk
r }
 z|
| W 5 d}
~
X Y n@ tk
r,   | jdt  tdd}
|
| Y nX W 5 | jd | }|dd |dd || X dS )z# Execute a 'ATLAS' request
        z7Removing user and group variables from the QGIS projectlizmap_userNlizmap_user_groupsREQUEST ZgetcapabilitiesZgetprintz3Adding user and group variables in the QGIS project  zOInvalid REQUEST parameter: must be one of GetCapabilities, GetPrint, found '{}'Unhandled exception:
{}  #Internal 'atlasprint' service error)
parametersr5   infocustomVariablespopsetCustomVariablesgetlowerget_capabilitiesheadersr   r   list	get_printr   r$   r,   	Exceptionr#   	traceback
format_exc)r%   r?   r   r@   paramsZ
custom_varZrequest_paramrQ   rA   Zlizmap_grouperrr   r   r   executeRequestX   sB    



z AtlasPrintService.executeRequest)rW   r   r@   r   c                 C   s0   | |f}d}d|t |ddd}t|| dS )z7 Get atlas capabilities based on metadata file
        
atlasprintZsuccessr:   )r9   r:   )r(   metadataN)r	   r   )rW   r   r@   r6   Zplugin_namer+   r   r   r   rP      s    
z"AtlasPrintService.get_capabilities)rW   r   r@   rA   lizmap_user_groupr   c              
   C   s.  | d}| dd}| d}| d}	t| d| d}
z|sNtd|rtt|}| rttd	| |r|	rtd
|rzt|}W n tk
r   tdY nX |	rzdd |		dD }	W n tk
r   tdY nX dd |
 D }|r||d< d||d< tf ||d |
||	|d|}W nh tk
rp } ztdd|W 5 d}~X Y n6 tk
r   | jdt  tddY nX t|}| stdd|
j|d|
j |d z||  |  W n, tk
r(   | jd|
j  Y nX dS )z Get print document
        TEMPLATE
EXP_FILTERNSCALESCALESFORMATr$   zTEMPLATE is requiredzExpression is invalid: {}z*SCALE and SCALES can not be used together.zInvalid number in SCALE.c                 S   s   g | ]}t |qS r   )r0   ).0scaler   r   r   
<listcomp>   s     z/AtlasPrintService.get_print.<locals>.<listcomp>,zInvalid number in SCALES.c                 S   s"   i | ]\}}|  d kr||qS ))r]   r^   r_   r`   ra   MAPrC   SERVICEZDPIZ
EXCEPTIONSZLAYERZLIZMAP_OVERRIDE_FILTERZTRANSPARENTVERSIONLIZMAP_USERLIZMAP_USER_GROUPS)upper)rb   kvr   r   r   
<dictcomp>   s      z/AtlasPrintService.get_print.<locals>.<dictcomp>rA   rB   )r@   Zlayout_nameoutput_formatrc   scalesfeature_filterrE   z8ATLAS - Error from the user while generating the PDF: {}rF   rG   rH   i  zATLAS {} not foundr   r   z$Error occurred while reading {} file)rN   r   r   r   ZhasParserErrorr$   ZparserErrorStringr0   
ValueErrorsplititemsjoinr   r   rT   r5   r#   rU   rV   r   existsr9   r   valuer   r   
read_bytesunlink)r%   rW   r   r@   rA   r\   templaterq   rc   rp   ro   
expressionZadditional_paramsZoutput_pathepathr   r   r   rS      st    



	 

zAtlasPrintService.get_print)F)r-   r.   r/   boolr"   r1   r9   r:   r   Methodr>   r   r   rY   staticmethodr   rP   tuplerS   r2   r   r   r&   r   r3   >   s"    0
r3   )r   )"__doc__r   rU   pathlibr   typingr   	qgis.corer   r   qgis.serverr   r   r   
qgis.utilsr	   corer   r   r   r5   r   toolsr   r   __copyright____license__	__email__r1   r0   r   rT   r   r3   r   r   r   r   <module>   s    