#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
    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 os
import sys
import json
import requests
import argparse


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 header(api_key):
    return {
        'X-API-KEY': api_key
        #	'Content-type': 'multipart/form-data'
    }


def create_log(log, url, api_key):
    response = requests.post(
        url, json=log.log_creation(), headers=header(api_key)
    )

    if response.status_code != 200:
        print(
            'ERROR: Could not create LogMetaData for logfile {}'.format(
                log.logfile
            )
        )
        print('  Response status code: {}'.format(response.status_code))
        print('  Response:             \n{}'.format(response.text))
        print('  Request headers:      {}'.format(response.request.headers))
        print('  Request body:         {}'.format(response.request.body))
        sys.exit(5)

    data = response.json()
    if not 'logId' in data:
        print('ERROR: No log id returned')
        sys.exit(6)
    return data["logId"]


def upload_log(log_id, log, url, api_key):
    fileContent = open(log.logfile, 'rb')
    headers = header(api_key)
    headers["Accept"] = "application/json"
    response = requests.post(
        "{}/{}".format(url, log_id), data=fileContent, headers=headers
    )
    if response.status_code != 200:
        print('ERROR: Could not upload log for logfile {}'.format(log.logfile))
        print("Response status code: {}".format(response.status_code))
        print("Response:             \n{}".format(response.text))
        sys.exit(7)


def main(argv):
    input_file_path = None
    url = None
    api_key = None

    parser = argparse.ArgumentParser(
        description='Uploads logfiles to GNUBoat server'
    )
    parser.add_argument(
        'input_file',
        metavar='input_file_path',
        type=str,
        help=
        'JSON file with water, gauge, device, logfiles and correction data to be processed'
    )
    parser.add_argument(
        '-s',
        '--server',
        dest='server',
        type=str,
        help='Server host and port to upload the logsfiles to'
    )
    parser.add_argument(
        '-k',
        '--api-key',
        dest='api_key',
        type=str,
        help='API Key for authorisation'
    )
    arguments = parser.parse_args(argv)

    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

    if arguments.server is None:
        print('ERROR: No server specified')
        sys.exit(2)
    else:
        url = 'http://{}/mapservice/v1/logs'.format(arguments.server)

    if arguments.api_key is None:
        print('ERROR: No API key specified')
        sys.exit(2)
    else:
        api_key = arguments.api_key

    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, url, api_key)
        upload_log(log_id, log, url, api_key)
        print(' Finished {}'.format(log.logfile))


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