'''
    Copyright (C) 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.

    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 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import connexion
import flask
import os

from ..HttpErrors import MapserviceInternalServerError, MapserviceBadRequest, MapserviceNotFound

def tiles_tile_get(accuracy, resolution, zoom, x_tile, y_tile):
	if not 'TILES_CACHE_PATH' in flask.current_app.config or not os.access(flask.current_app.config['TILES_CACHE_PATH'], os.R_OK):
		raise MapserviceInternalServerError(detail='TILES_CACHE_PATH not configured or not accessible')
	tiles_cache_path = flask.current_app.config['TILES_CACHE_PATH']
	
	if not 'TILES_DENSITIES' in flask.current_app.config:
		raise MapserviceInternalServerError(details='TILES_DENSITIES not configured')
	tiles_densities = flask.current_app.config['TILES_DENSITIES']
	
	if not 'TILES_DENSITY_BASEE' in flask.current_app.config:
		raise MapserviceInternalServerError(details='TILES_DENSITY_BASEE not configured')
	tiles_densitiy_base = flask.current_app.config['TILES_DENSITY_BASEE']
	
	if not 'TILES_SKIP_EMPTY' in flask.current_app.config:
		raise MapserviceInternalServerError(details='TILES_SKIP_EMPTY not configured')
	tiles_skip_empty = flask.current_app.config['TILES_SKIP_EMPTY']
	
	if accuracy == 'high':
		accuracy = '{}_{}'.format(max(tiles_densities), tiles_densitiy_base)
	elif accuracy == 'low':
		accuracy = '{}_{}'.format(min(tiles_densities), tiles_densitiy_base)
	else:
		raise MapserviceBadRequest(details='No valid accuracy requested. Valid are high, low. Requested was: {}'.format(accuracy))
	
	tile__empty_path = os.path.join(tiles_cache_path, '{}/{}/empty_tile.png'.format(accuracy, resolution))
	tile_path = os.path.join(tiles_cache_path, '{}/{}/{}/{}/{}.png'.format(accuracy, resolution, zoom, x_tile, y_tile))
	if not os.path.isfile(tile_path):
		if not tiles_skip_empty or not os.path.isfile(tile__empty_path):
			raise MapserviceNotFound(detail='Tile ({}, {}) for accuracy {} with resolution {} at zoomlevel {} not found'.format(x_tile, y_tile, accuracy, resolution, zoom))
		tile_path = tile__empty_path
	
	response = flask.send_file(tile_path, mimetype='image/png', as_attachment=True, attachment_filename='{}.png'.format(y_tile))
	response.direct_passthrough = False
	#response.headers['Content-Transfer-Encoding']='base64'
	return response
