#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
    Copyright (C) 2020 EngSaS - 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 os
import sys
import json
import getpass
import argparse
from urllib3.exceptions import RequestError

from gnuboat.mapservice_client.configuration import Configuration as MsConfiguration
from gnuboat.mapservice_client.api_client import ApiClient as MsApiClient
from gnuboat.mapservice_client.exceptions import ApiException as MsApiException
from gnuboat.mapservice_client.api.logs_api import LogsApi as MsLogsApi
from gnuboat.mapservice_client.models.log_creation import LogCreation as MsLogCreation
from gnuboat.mapservice_client.api.devices_api import DevicesApi as MsDevicesApi


class Log:
    """
		Workaround for @dataclass, until python 3.7 is available in main distros
	"""
    def __init__(
        self, water_id, device_id, gauge_id, gauge_height, comment, logfile
    ):
        self.water_id = water_id
        self.device_id = device_id
        self.gauge_id = gauge_id
        self.gauge_height = gauge_height
        self.comment = comment
        self.logfile = logfile

    def log_creation(self):
        return {
            'water': self.water_id,
            'device': self.device_id,
            'gauge': self.gauge_id,
            'gaugeHeight': self.gauge_height,
            'comment': self.comment
        }


def to_int(value_string):
    try:
        return int(value_string)
    except:
        return None


def to_float(value_string):
    try:
        return float(value_string)
    except:
        return None


def mapservice_configuration(username, password, api_key, base_url = None):
    configuration = MsConfiguration()
    if base_url is not None:
        configuration.host = base_url
    if api_key:
        configuration.api_key['X-API-KEY'] = api_key
    else:
        configuration.username = username
        configuration.password = password
    return configuration


def handle_mapservice_error(exception, error_message):
    if isinstance(exception, MsApiException):
        response_body = json.loads(exception.body)
        print(error_message)
        print('  Status code: {}'.format(response_body['status']))
        print('  Details:     {}'.format(response_body['detail']))
    elif isinstance(exception, RequestError):
        print('Could not connect to server {}:{}/{}'.format(
            exception.pool.host, exception.pool.port, exception.url
        ))
    else:
        print('An unhandled error occured: {}'.format(repr(exception)))
    sys.exit(5)


def display_devices(configuration):
    with MsApiClient(configuration) as api_client:
        try:
            devices = MsDevicesApi(api_client).devices_get()
        except Exception as e:
            handle_mapservice_error(e, 'ERROR: Could not get devices')

    if len(devices) < 0:
        print('You have no devices at {}').format(configuration.host)
        return

    print('Id     Name                          Sensor Depth Comment')
    for device in devices:
        print('{:6d} {:30s} {:11f} {}'.format(
            device.device_id, device.name,
            device.sensor_depth, device.comment
        ))

def create_log(log, configuration):
    with MsApiClient(configuration) as api_client:
        try:
            log_metadata = MsLogsApi(api_client).logs_log_create(log_creation = log.log_creation())
        except Exception as e:
            error_message = ('ERROR: Could not create Log entry for '
                             'logfile {}').format(log.logfile)
            handle_mapservice_error(e, error_message)
    return log_metadata.log_id


def upload_log(log_id, log, configuration):
    with open(log.logfile, 'rb') as logfilehandle:
        file_content = logfilehandle.read()
    with MsApiClient(configuration) as api_client:
        try:
            log_metadata = MsLogsApi(api_client).logs_log_upload(log_id = log_id, body = file_content)
        except MsApiException as e:
            handle_mapservice_error(e, log)


def load_and_upload_logs(input_file_path, configuration):
    logs_checked = []
    print('Checking input from {}'.format(input_file_path))
    with open(input_file_path, 'r') as input_file:
        logs = json.load(input_file)
        for log in logs:
            if not 'water' in log:
                print('ERROR: No water in log {}'.format(json.dumps(log)))
                sys.exit(4)
            water_id = to_int(log['water'])
            if not water_id:
                print(
                    'ERROR: Could not convert water to int {}'.format(
                        log['water']
                    )
                )
                sys.exit(4)

            if not 'gauge' in log:
                print('ERROR: No gauge in log {}'.format(json.dumps(log)))
                sys.exit(4)
            gauge_id = to_int(log['gauge'])
            if not gauge_id:
                print(
                    'ERROR: Could not convert gauge to int {}'.format(
                        log['gauge']
                    )
                )
                sys.exit(4)

            if not 'device' in log:
                print('ERROR: No device in log {}'.format(json.dumps(log)))
                sys.exit(4)
            device_id = to_int(log['device'])
            if not device_id:
                print(
                    'ERROR: Could not convert device to int {}'.format(
                        log['device']
                    )
                )
                sys.exit(4)

            if not 'gaugeHeight' in log:
                print(
                    'ERROR: No gaugeHeight in log {}'.format(json.dumps(log))
                )
                sys.exit(4)
            gauge_height = to_float(log['gaugeHeight'])
            if not gauge_height:
                print(
                    'ERROR: Could not convert gaugeHeight to float {}'.format(
                        log['gaugeHeight']
                    )
                )
                sys.exit(4)

            if not 'file' in log:
                print('ERROR: No file in log {}'.format(json.dumps(log)))
                sys.exit(4)

            comment = ''
            if 'comment' in log:
                comment = log['comment']

            logfile = os.path.join(os.path.dirname(__file__), log['file'])
            if not os.path.exists(logfile):
                logfile_rel = os.path.join(
                    os.path.dirname(input_file_path), log['file']
                )
                if not os.path.exists(logfile_rel):
                    print(
                        'ERROR: Logfile not found at {} or {}'.format(
                            logfile, logfile_rel
                        )
                    )
                    sys.exit(4)
                else:
                    logfile = logfile_rel
            logs_checked.append(
                Log(
                    water_id, device_id, gauge_id, gauge_height, comment,
                    logfile
                )
            )

    print('Uploading {} logs'.format(len(logs_checked)))
    for log in logs_checked:
        log_id = create_log(log, configuration)
        upload_log(log_id, log, configuration)
        print(' Finished {}'.format(log.logfile))


def main(argv):
    input_file_path = None
    base_url = None
    username = None
    password = None
    api_key = None

    parser = argparse.ArgumentParser(
        description='Uploads logfiles to GNUBoat server'
    )
    parser.add_argument(
        'input_file',
        metavar='input_file_path',
        type=str,
        nargs='?',
        help=
        'JSON file with water, gauge, device, logfiles and correction data to be processed'
    )
    parser.add_argument(
        '-b',
        '--base',
        dest='base_url',
        type=str,
        default=MsConfiguration().host,
        help='Server base url to upload the logsfiles to'
    )
    parser.add_argument(
        '-k',
        '--api-key',
        dest='api_key',
        type=str,
        help='API Key for authorisation'
    )
    parser.add_argument(
        '-d',
        '--devices',
        dest='devices',
        action='store_true',
        help='Display a list of your devices on the server'
    )
    arguments = parser.parse_args(argv)


    # handle base parameter
    if arguments.base_url is not None:
        if arguments.base_url.endswith('/'):
            base_url = arguments.base_url[:-1]
        else:
            base_url = arguments.base_url

    if arguments.api_key is None:
        username = input('Username: ')
        if not username:
            print('ERROR: No username given')
            sys.exit(2)
        password = getpass.getpass()
        if not password:
            print('ERROR: No password given')
            sys.exit(2)
    else:
        api_key = arguments.api_key
    configuration = mapservice_configuration(username, password, api_key, base_url)

    if arguments.devices:
        display_devices(configuration)
        sys.exit(0)

    if arguments.input_file is None:
        print('ERROR: No input file specified')
        sys.exit(2)
    elif not os.path.exists(arguments.input_file):
        print(
            'ERROR: Specified input file does not exists: {}'.format(
                arguments.input_file
            )
        )
        sys.exit(3)
    else:
        input_file_path = arguments.input_file

    load_and_upload_logs(input_file_path, configuration)


if __name__ == "__main__":
    main(sys.argv[1:])
