"""
    Service MG/sources/calls/preview
    to preview the view and delete the foreing table.
"""
from io import StringIO
import csv

from tools import const
from tools.layer import Layer


def post(task, user=None, input_layer: Layer = None,
         params: dict=None, overwrite=None):
    """

        Create a foreign table through wrapper of the vector and thematic layers
        to obtain its information and
        then be able to create a view to preview the attributes selected
        by the user.
        The foreign server created will be delimited in the preview service.
        Statistical information is supplied for raster layers and
        the contained files are supplied for generic layers.

    Parameters
    ----------
    user: str
        User ID
    input_layer : Layer
        Object Input Layer
    params: dict
        Dict with attributes, name view or sql clauses
    overwrite: bool
        Bool to show whether the view could be overwrited if exist

    Returns
    -------
    dict
        Dict with status and message CSV

    Examples
    --------
    >>> import requests
    >>> input_layer = {'protocol': 'PostgreSQL',
    ...    'type': 'VECTOR',
    ...    'driver_type': 'PostgreSQL',
    ...    'ip': '192.168.1.43',
    ...    "domain": '',
    ...    'port': '30030',
    ...    'user': 'srm_postgres_1',
    ...    'password': 'pg_produccion#1',
    ...    'database_name': 'imetadata',
    ...    'schema': 'TEST',
    ...    'table_view_name': 'edificios'}
    >>> params = {'view': 'edificios',
    ...            'select': '*',
    ...            'where': '',
    ...            'groupBy': '',
    ...            'having': '',
    ...            'orderBy': '',
    ...            'limit': ''}
    >>> parameters={'user':'TEST', "input_layer":input_layer, "params":params, "overwrite":True}
    >>> response = requests.post('<Server_IP>:<Server_PORT>/MG/sources/calls/preview',
    ... json=parameters)
    >>> response.json()
        {'task_id': 'XoiRl9'}

    """
    res_preview = input_layer.preview()
    if isinstance(res_preview, bool):
        response = input_layer.create(params=params, overwrite=overwrite)
        if response[0] != [True]:
            obj = {'status': 'Error',
                   'message': 'Duplicate Source:  "{}" already exists'.format(
                       params["view"])}
            return obj
        rows = [response[1], *response[2]]
        input_layer.remove(input_layer)
    else:
        if len(res_preview[1]) == 1:
            rows = [res_preview[0], res_preview[1]]
        else:
            rows = [res_preview[0], *res_preview[1]]

    output = StringIO()
    csv_writer = csv.writer(output, dialect='excel', delimiter=',')
    csv_writer.writerows(rows)
    string_csv = output.getvalue()
    obj = {'status': 'ok', 'message': string_csv}
    return obj


POST_REQUEST = {
    'function': post,
    'parser': const.PARSER_SOURCES
}