#!/usr/bin/env python
# -*- coding:utf-8 -*-

# Copyright (C) 2013, 2014
# Daniel Belasco Rogers <http://planbperformance.net/dan>,
# Peter Vasil <mail@petervasil.net>
#
# 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 sys
import os
from datetime import datetime
from optparse import OptionParser
import gpx2spatialite as g2s


def parseargs():
    """
    parse command line arguments and define options etc
    """
    usage = "usage: %prog [options] -d <database> -u <username> "\
            "/path/to/gpx-file.gpx or /path/to/folder"
    optparser = OptionParser(usage,
                             version="%prog {0}".format(g2s.__version__))
    optparser.add_option("-d",
                         "--database",
                         dest="dbasepath",
                         metavar="FILE",
                         help="Define path to alternate database \
                         (mandatory option)")

    optparser.add_option("-u",
                         "--user",
                         dest="user",
                         metavar="NAME",
                         help="User name (mandatory option)")

    optparser.add_option("-s",
                         "--skip-locations",
                         dest="skip_locs",
                         default=False,
                         action="store_true",
                         help="Skip querying locations for points (faster)")

    optparser.add_option('-q',
                         '--quiet',
                         dest='quiet',
                         default=False,
                         action='store_true')

    (options, args) = optparser.parse_args()

    def print_option_missing_and_exit():
        print('\nError: mandatory option is missing\n')
        optparser.print_usage()
        sys.exit(2)

    if options.dbasepath is None:
        print_option_missing_and_exit()

    dbpath = os.path.expanduser(options.dbasepath)

    quiet = options.quiet

    if len(args) < 1:
        print_option_missing_and_exit()

    if options.user is None:
        print_option_missing_and_exit()

    user = options.user

    filepaths_tmp = args
    filepaths = []
    for f in filepaths_tmp:
        if g2s.checkfile(f):
            filepaths.append(f)
        else:
            print("{0} is not a file or directory".format(f))

    skip_locs = options.skip_locs

    return filepaths, user, dbpath, skip_locs, quiet


def main():
    """
    you know what 'main' does - run everything in the right order and
    print helpful messages to stdout
    """
    # for timing (rough)
    starttime = datetime.now()

    # -------------------------------------------------------------------------

    filepaths, username, dbpath, skip_locs, quiet = parseargs()

    g2s.set_print_verbose(not quiet)

    conn = g2s.get_connection(dbpath)
    cursor = conn.cursor()

    # -------------------------------------------------------------------------

    gpx_filepaths = g2s.read_filepaths(filepaths, ".gpx")
    g2s.print_cmdline("\nFound {0} .gpx files.\n".format(len(gpx_filepaths)))

    if len(gpx_filepaths) == 0:
        print("No input files!")
        sys.exit(1)

    # -------------------------------------------------------------------------

    if not g2s.check_if_table_exists(conn, "users"):
        msg = ("Unable to find database table \"users\".\n Use "
               "`gpx2spatialite_create_db` to create the database beforehand.")
        print(msg)
        cursor.close()
        conn.close()
        sys.exit(1)

    userid = g2s.get_user_id(cursor, username)
    if userid == -1:
        # user name is not in database - ask to add
        if g2s.checkadd(username):
            msg = "User {0} sucessfully added to database".format(username)
            g2s.print_cmdline(msg)
            userid = g2s.insert_user(cursor, username)
            conn.commit()
        else:
            print("Please run again specifying a known user:")
            cursor.close()
            conn.close()
            sys.exit(1)

    # -------------------------------------------------------------------------

    get_loc_func = None if skip_locs else g2s.get_location_func(cursor)

    # -------------------------------------------------------------------------

    for filepath in gpx_filepaths:

        # ---------------------------------------------------------------------

        if g2s.check_if_gpxfile_exists(cursor, filepath) is True:
            g2s.print_cmdline("File {0} already in database".format(filepath))
            continue

        # ---------------------------------------------------------------------

        parsing_starttimep = datetime.now()
        g2s.print_cmdline("#" * 48)
        g2s.print_cmdline("Parsing points in {0}".format(filepath))

        # ---------------------------------------------------------------------

        trkpts, trklines, firsttimestamp, lasttimestamp, wpts, seg_uuids = \
            g2s.extractpoints(filepath, get_loc_func, False)

        # ---------------------------------------------------------------------

        seg_dict = g2s.insert_segments(cursor, seg_uuids)

        # ---------------------------------------------------------------------

        msg = "File first timestamp: {0}, last timestamp: {1}"
        g2s.print_cmdline(msg.format(firsttimestamp, lasttimestamp))

        if firsttimestamp == 0 or lasttimestamp == 0:
            continue
            g2s.print_cmdline("Skipping importing {0}.".format(filepath))

        # ---------------------------------------------------------------------

        parsing_endtime = datetime.now()
        parsing_duration = parsing_endtime - parsing_starttimep
        msg = "\nParsing {0} points and {1} waypoints from gpx file took {2}"
        g2s.print_cmdline(msg.format(len(trkpts), len(wpts), parsing_duration))

        # ---------------------------------------------------------------------

        db_starttime = datetime.now()

        # print "Entering file into database"
        g2s.enterfile(filepath, cursor, userid, firsttimestamp, lasttimestamp)

        file_uid = g2s.get_currentfileid(cursor)

        # print "Entering points into database"
        g2s.enterpoints(cursor, userid, trkpts, file_uid, seg_dict)

        # print "Entering lines into database"
        g2s.enterlines(cursor, userid, trklines, file_uid, seg_dict)

        # print entering waypoints into database
        g2s.enterwaypoints(cursor, userid, wpts, file_uid)

        # ---------------------------------------------------------------------

        conn.commit()

        # ---------------------------------------------------------------------
        db_endtime = datetime.now()
        db_duration = db_endtime - db_starttime
        msg = "Entering into database took {0}"
        g2s.print_cmdline(msg.format(db_duration))

        # ---------------------------------------------------------------------

    cursor.close()
    conn.close()

    endtime = datetime.now()
    g2s.print_cmdline("#" * 48)
    g2s.print_cmdline("Script took {0}\n".format(endtime - starttime))

if __name__ == '__main__':
    sys.exit(main())
