import os
from pgadmin.misc.file_manager import Filemanager
from pgadmin.utils import get_storage_directory
from pgadmin.utils.ajax import make_json_response, bad_request, \
    success_return, internal_server_error, unauthorized

try:
    from urllib import unquote
except ImportError:
    from urllib.parse import unquote


def save_query_to_file(file_data):
    # retrieve storage directory path
    storage_manager_path = get_storage_directory()

    # generate full path of file
    file_path = unquote(file_data['file_name'])
    if hasattr(str, 'decode'):
        file_path = unquote(
            file_data['file_name']
        ).encode('utf-8').decode('utf-8')

    if not file_path.endswith('.sql'):
        file_path = file_path + ".sql"

    try:
        Filemanager.check_access_permission(storage_manager_path, file_path)
    except Exception as e:
        return internal_server_error(errormsg=str(e))

    # lstrip() returns a copy of the string
    # in which all chars have been stripped
    # from the beginning of the string (default whitespace characters).
    if storage_manager_path is not None:
        file_path = os.path.join(
            storage_manager_path,
            file_path.lstrip('/').lstrip('\\')
        )

    if hasattr(str, 'decode'):
        file_content = file_data['file_content']
    else:
        file_content = file_data['file_content'].encode()

    # write to file
    try:
        with open(file_path, 'wb+') as output_file:
            if hasattr(str, 'decode'):
                output_file.write(file_content.encode('utf-8'))
                return file_path
            else:
                output_file.write(file_content)
                return file_path
    except IOError as e:
        if e.strerror == 'Permission denied':
            err_msg = "Error: {0}".format(e.strerror)
        else:
            err_msg = "Error: {0}".format(e.strerror)
        return internal_server_error(errormsg=err_msg)
    except Exception as e:
        err_msg = "Error: {0}".format(e.strerror)
        return internal_server_error(errormsg=err_msg)
