# -*- coding: utf-8 -*-
'''
    Copyright (C) 2016 - 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 re
import pynmea2
import datetime
from pytz import timezone
import traceback
import math

from gnuboat_common.datahandler import logdataset


class LogParsingResult:
    def __init__(self):
        self._success = False
        self._errors = []

    def error_add(self, error):
        self._errors.append(error)

    def errors(self):
        return self._errors

    def messages(self):
        if len(self._errors) > 0:
            return True
        return False

    def succeeded(self, status):
        self._success = status

    def success(self):
        return self._success


"""@class LogHandler
"""


class LogHandler:
    def __init__(self, log_directory=None):
        self._regex_nmea_sentence = re.compile(
            r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+\*[\da-zA-Z]+)$"
        )
        self._regex_nmea_sentence_without_checksum = re.compile(
            r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+)\*[\da-zA-Z]+$"
        )
        self._regex_nmea_position_latitude = re.compile(
            r"^([0-9]{2})([0-9]{2}\.[0-9]+)$"
        )
        self._regex_nmea_position_longitude = re.compile(
            r"^([0-9]{3})([0-9]{2}\.[0-9]+)$"
        )
        self._log_directory = log_directory
        self._nmea_file = None
        self._nmea_file_date = None

    def gnuboat_write(
        self, gps_fix, gps_time, dataset, transducer_valid, log_verbose,
        log_system_time
    ):
        # Only log, if we have a gps fix
        if gps_fix < 2:
            if not log_verbose:
                return
            gps_status = 'V'
            mode = 'N'
            if gps_time is None:
                gps_time = datetime.datetime.utcnow()

        nmea_file_date_should = datetime.datetime.utcnow().strftime("%Y-%m-%d")
        mode = 'A'
        if self._nmea_file == None or self._nmea_file_date is None or self._nmea_file_date != nmea_file_date_should:
            if self._nmea_file:
                self._nmea_file.close()
            try:
                self._nmea_file_date = nmea_file_date_should
                nmea_log_file = 'nmea0183-{}.log'.format(self._nmea_file_date)
                self._nmea_file = open(
                    os.path.join(self._log_directory, nmea_log_file), 'a', 0
                )
            except IOError as error:
                print('Could not open the logfile: {}'.format(error))
                return False
        else:
            nmea_log_file = self._nmea_file.name

        latitude = self._degreesDecimalToNmea(dataset.latitude())
        longitude = self._degreesDecimalToNmea(dataset.longitude())

        logsystemtime = ""
        if log_system_time:
            logsystemtime = '{}: '.format(
                datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
            )

        try:
            self._nmea_file.write(
                '{}{}\r\n'.format(
                    logsystemtime,
                    str(
                        pynmea2.RMC(
                            'GN', 'RMC', (
                                gps_time.strftime("%H%M%S"),
                                dataset.gps_status(), '{:02d}{:07.4f}'.format(
                                    latitude['degrees'], latitude['minutes']
                                ), dataset.latitude_direction(),
                                '{:03d}{:07.4f}'.format(
                                    longitude['degrees'], longitude['minutes']
                                ), dataset.longitude_direction(),
                                '{:04.1f}'.format(dataset.speed_over_ground()),
                                '{:04.1f}'.format(
                                    dataset.course_over_ground()
                                ), gps_time.strftime("%d%m%y"), '', '', mode
                            )
                        )
                    )
                )
            )
            if transducer_valid:
                self._nmea_file.write(
                    '{}{}\r\n'.format(
                        logsystemtime,
                        str(
                            pynmea2.DPT(
                                'SD', 'DPT', (
                                    '{:05.2f}'.format(dataset.water_depth()
                                                      ), '00.00'
                                )
                            )
                        )
                    )
                )
                self._nmea_file.write(
                    '{}{}\r\n'.format(
                        logsystemtime,
                        str(
                            pynmea2.MTW(
                                'YX', 'MTW', (
                                    '{:04.1f}'.format(
                                        dataset.water_temperature()
                                    ), 'C'
                                )
                            )
                        )
                    )
                )
            return True
        except:
            print('Failed writing to logfile {}'.format(nmea_log_file))
            print(traceback.format_exc())
            return False
        return False

    def gnuboat_close(self):
        if self._nmea_file:
            self._nmea_file.close()

    def parse_nmea_sentence(self, line, checksum_ingore=False):
        line = line.strip()
        if checksum_ingore:
            matches = self._regex_nmea_sentence_without_checksum.match(line)
        else:
            matches = self._regex_nmea_sentence.match(line)
        if matches is None:
            return None
        return {
            'log_timestamp':
                matches.group(1),
            'nmea_sentence':
                pynmea2.parse(matches.group(2), not checksum_ingore)
        }

    """	Reads the original gnuboat log files and calls a callable function on all complete LogDataset
		callback must be of a function wich excepts the LogDataset as a parameter.
	"""

    def gnuboat_read_file(
        self,
        input_file_path,
        callback,
        checksums_fix=False,
        errors_ignore=False
    ):
        result = LogParsingResult()

        # reading input file
        try:
            input_file = open(input_file_path, 'r')
        except IOError as error:
            result.error_add(
                'ERROR: Could not open the input file: {}'.format(error)
            )
            result.succeeded(False)
            return result
        result = self.gnuboat_read(
            input_file, callback, checksums_fix, errors_ignore=False
        )
        input_file.close()
        return result

    """	Reads the original gnuboat log from input_list and calls a callable function on all complete LogDataset
		callback must be of a function wich excepts the LogDataset as a parameter.
	"""

    def gnuboat_read(
        self, input_list, callback, checksums_fix=False, errors_ignore=False
    ):
        result = LogParsingResult()

        current_row = 1
        last_row = None
        for line in input_list:
            nmea_sentence = self.parse_nmea_sentence(line, checksums_fix)
            if nmea_sentence is None:
                result.error_add(
                    'INFO: Failed to parse nmea sentence ({}) at line {}'.
                    format(line.strip(), current_row)
                )
                if not errors_ignore:
                    result.succeeded(False)
                    return result
            else:
                nmea_sentence = nmea_sentence['nmea_sentence']
                if nmea_sentence.sentence_type == 'RMC':
                    if last_row is not None:
                        callback(last_row)
                    last_row = logdataset.LogDataset()
                    last_row.datetime_set(
                        '{} {}'.format(
                            nmea_sentence.datestamp, nmea_sentence.timestamp
                        )
                    )
                    last_row.gps_status_set(nmea_sentence.status)
                    last_row.latitude_set(
                        self._nmeaLatitudeToDecimalDegrees(
                            nmea_sentence.lat, current_row
                        )
                    )
                    last_row.latitude_direction_set(nmea_sentence.lat_dir)
                    last_row.longitude_set(
                        self._nmeaLongitudeToDecimalDegrees(
                            nmea_sentence.lon, current_row
                        )
                    )
                    last_row.longitude_direction_set(nmea_sentence.lon_dir)
                    last_row.speed_over_ground_set(
                        self._to_float(
                            nmea_sentence.spd_over_grnd, current_row
                        )
                    )
                    last_row.course_over_ground_set(
                        self._to_float(nmea_sentence.true_course, current_row)
                    )
                    last_row.water_depth_set(None)
                    last_row.water_temperature_set(None)
                elif nmea_sentence.sentence_type == 'DPT' and last_row is not None:
                    last_row.water_depth_set(
                        self._to_float(nmea_sentence.depth, current_row)
                    )
                elif nmea_sentence.sentence_type == 'MTW' and last_row is not None:
                    last_row.water_temperature_set(
                        self._to_float(nmea_sentence.temperature, current_row)
                    )
            current_row += 1
        if last_row is not None:
            callback(last_row)
        result.succeeded(True)
        return result

    def _to_float(self, string, current_row):
        try:
            return float(string)
        except ValueError as error:
            try:
                return int(string)
            except ValueError as error:
                print(
                    'INFO: Failed to convert value from line {} into numeric: {}\n      Message: {}'
                    .format(current_row, string, error)
                )
                return 0

    def _nmeaLatitudeToDecimalDegrees(self, nmea_value, current_row):
        if self._to_float(nmea_value, current_row) == 0:
            return 0

        matches = self._regex_nmea_position_latitude.match(nmea_value)
        if matches is None:
            print(
                'INFO: Failed to convert latitude position value from line {} into decimal degrees: {}'
                .format(current_row, nmea_value)
            )
            return
        decimalDegrees = self._to_float(matches.group(1), current_row)
        decimalMinutes = self._to_float(matches.group(2), current_row)
        return decimalDegrees + (decimalMinutes / 60.0)

    def _nmeaLongitudeToDecimalDegrees(self, nmea_value, current_row):
        if self._to_float(nmea_value, current_row) == 0:
            return 0

        matches = self._regex_nmea_position_longitude.match(nmea_value)
        if matches is None:
            print(
                'INFO: Failed to convert longitude position value from line {} into decimal degrees: {}'
                .format(current_row, nmea_value)
            )
            return
        decimalDegrees = self._to_float(matches.group(1), current_row)
        decimalMinutes = self._to_float(matches.group(2), current_row)
        return decimalDegrees + (decimalMinutes / 60.0)

    def _degreesDecimalToNmea(self, decimalDegrees):
        degrees = int(math.floor(decimalDegrees))
        minutes = 60.0 * (decimalDegrees - degrees)
        return {'degrees': degrees, 'minutes': minutes}
