#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
    Copyright (C) 2016 - 2017 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 argparse
import sys
import pynmea2
from enum import Enum
import csv

class Format(Enum):
    CSV = 1

input_file_path = None
output_file_path = None
output_format_option = None
output_format = Format.CSV
errors_ignore = False

def toFloat(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 %s into numeric: %s\n      Message: %s' % (current_row, string, error)
           return 0

def main(argv):
    formats = []
    for file_format in Format:
      formats.append(file_format.name)

    parser = argparse.ArgumentParser(description="Convert gnuboat logfiles into other formats")
    parser.add_argument('-f', '--format', dest='output_format', metavar='output_format', type=str,
                        help='Format of the output file.', choices=formats, default='CSV')
    parser.add_argument('-i', '--ignore-errors', dest='errors_ignore', metavar='errors_ignore', type=bool,
                        help='Ignore any errors reading the log file', default=False)
    parser.add_argument('input_file', metavar='input_file_path', type=str,
                        help='File to be converted (input)')
    parser.add_argument('output_file', metavar='output_file_path', type=str,
                        help='Write the converted content to file (output)')
    arguments = parser.parse_args(argv)
   
    if arguments.output_format is not None:
        format_found = False
        for file_format in Format:
            if file_format.name == arguments.output_format:
               output_format = file_format.value
               format_found = True
        if not format_found:
            print 'Invalid input format specified: %s' % arguments.output_format
            sys.exit(1)

    if arguments.errors_ignore is not None:
        errors_ignore = arguments.errors_ignore
            
    if arguments.input_file is None:
        print 'No input file specified'
        sys.exit(2)
    elif not os.path.exists(arguments.input_file):
        print 'Specified input file does not exists: %s' % arguments.input_file
        sys.exit(3)
    else:
        input_file_path = arguments.input_file
        
    if arguments.output_file is None:
        print 'No output file specified'
        sys.exit(2)
    elif not os.path.exists(os.path.dirname(arguments.output_file)):
        print 'Specified directory of output file does not exists: %s' % arguments.output_file
        sys.exit(3)
    else:
        output_file_path = arguments.output_file

    try:
        output_file = open(output_file_path, 'w', 0)
    except IOError as error:
        print "Could not open the output file: %s" % error
        sys.exit(3)
        
    output_file_csv = None
    if output_format == Format.CSV.value:
        fields = ['datetime', 'gps_status', 'latitude', 'latitude_direction', 'longitude',
                  'longitude_direction', 'speed_over_ground', 'course_over_ground' ,
                  'water_depth', 'water_temperature']
        output_file_csv = csv.DictWriter(output_file, delimiter=' ', quotechar='"',
                                         quoting=csv.QUOTE_NONNUMERIC, fieldnames=fields)
        output_file_csv.writeheader()

    # reading input file
    nmea_errors='raise'
    if errors_ignore:
        nmea_errors='ignore'
    nmea_file = pynmea2.NMEAFile(input_file_path)
    current_row = 1
    last_row = None
    for nmea_sentence in nmea_file:
        if output_format == Format.CSV.value:
            if nmea_sentence.sentence_type == 'RMC':
                if last_row is not None:
                    output_file_csv.writerow(last_row)
                last_row = {'datetime': '%s %s' % (nmea_sentence.datestamp, nmea_sentence.timestamp),
                            'gps_status': nmea_sentence.status,
                            'latitude': toFloat(nmea_sentence.lat, current_row),
                            'latitude_direction': nmea_sentence.lat_dir,
                            'longitude': toFloat(nmea_sentence.lon, current_row),
                            'longitude_direction': nmea_sentence.lon_dir,
                            'speed_over_ground': toFloat(nmea_sentence.spd_over_grnd, current_row),
                            'course_over_ground': toFloat(nmea_sentence.true_course, current_row),
                            'water_depth': None,
                            'water_temperature': None}
            elif nmea_sentence.sentence_type == 'DBT' and last_row is not None:
                last_row['water_depth'] = toFloat(nmea_sentence.depth_meters, current_row)
            elif nmea_sentence.sentence_type == 'MTW' and last_row is not None:
                last_row['water_temperature'] = toFloat(nmea_sentence.temperature, current_row)
        current_row += 1
    if last_row is not None:
        output_file_csv.writerow(last_row)  
        
    output_file.close()
    sys.exit(0)

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