#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
    Copyright (C) 2017 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 rrdtool
import argparse
import random
import time
import sys
import os

from gnuboat.common.datahandler import rrd_handler as rrdhandler

# default values for command line arguments
rrdfile = "/var/lib/gnuboat/gnuboat.rrd"
# in seconds
logperiod = 2
duration = 24 * 60 * 60
latitude_min = -90
latitude_max = 90
longitude_min = -180
longitude_max = 180


def main(argv):
    global rrdfile
    global duration
    global latitude_min
    global latitude_max
    global longitude_min
    global longitude_max
    global logperiod

    parser = argparse.ArgumentParser(
        description=
        'Generates test data for gnuboat webservice and fills the rrd database'
    )
    parser.add_argument(
        '-f',
        '--file',
        dest='rrd_database',
        metavar='rrd_database',
        type=str,
        help='File path of the rrd database to fill',
        default="/var/lib/gnuboat/gnuboat.rrd"
    )
    parser.add_argument(
        '-lat-min',
        '--latitude-min',
        dest='lat_min',
        metavar='lat_min',
        type=float,
        help='Minimum latitude generated',
        default=latitude_min
    )
    parser.add_argument(
        '-lat-max',
        '--latitude-max',
        dest='lat_max',
        metavar='lat_max',
        type=float,
        help='Maximum latitude generated',
        default=latitude_max
    )
    parser.add_argument(
        '-lon-min',
        '--longitude-min',
        dest='lon_min',
        metavar='lon_min',
        type=float,
        help='Minimum longitude generated',
        default=longitude_min
    )
    parser.add_argument(
        '-lon-max',
        '--longitude-max',
        dest='lon_max',
        metavar='lon_max',
        type=float,
        help='Maximum longitude generated',
        default=longitude_max
    )
    parser.add_argument(
        '-l',
        '--logperiod',
        dest='logperiod',
        metavar='logperiod',
        type=int,
        help='Period of data generation (seconds between two values)',
        default=logperiod
    )
    arguments = parser.parse_args(argv)

    if arguments.rrd_database is not None:
        rrdfile = arguments.rrd_database

    if arguments.lat_min is not None:
        latitude_min = arguments.lat_min
    if arguments.lat_max is not None:
        latitude_max = arguments.lat_max

    if arguments.lon_min is not None:
        longitude_min = arguments.lon_min
    if arguments.lon_max is not None:
        longitude_max = arguments.lon_max

    if arguments.logperiod is not None:
        logperiod = arguments.logperiod

    if not os.path.exists(os.path.dirname(rrdfile)):
        print(
            'rrd database directory not found {}'.format(
                os.path.dirname(rrdfile)
            )
        )
        parser.print_help()
        sys.exit(2)

    timestamp = int(time.time())
    start_time = timestamp - duration - logperiod

    if os.path.isfile(rrdfile):
        print('Removing old database {}'.format(rrdfile))
        os.remove(rrdfile)

    print('Creating {}'.format(rrdfile))
    rrdhandler.rrd_create_database(rrdfile, logperiod, str(start_time))

    print(
        'Filling database inside [{}, {}] --> [{}, {}]...'.format(
            latitude_min, longitude_min, latitude_max, longitude_max
        )
    )
    for current_time in range(timestamp - duration, timestamp, logperiod):
        latitude = random.uniform(latitude_min, latitude_max)
        longitude = random.uniform(longitude_min, longitude_max)
        speedThroughWater = random.randint(0, 10)
        speedOverGround = random.randint(-2, 15)
        courseOverGround = random.randint(0, 360)
        waterDepth = random.randint(0, 20)
        waterTemperature = random.randint(2, 25)
        gpsFix = 3
        # update rrd database for the webservice
        rrdhandler.rrd_update(
            rrdfile, '{}:{}:{}:{}:{}:{}:{}:{}:{}'.format(
                current_time, latitude, longitude, speedThroughWater,
                speedOverGround, courseOverGround, waterDepth,
                waterTemperature, gpsFix
            )
        )


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