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

# Copyright (C) 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/].

"""

Separate script to handle updating locations in the database if you
have changed citydefs by adding locations or redifining existing ones.

"""

import sys
from optparse import OptionParser
from os import path
from datetime import datetime
import gpx2spatialite as g2s


def parseargs():
    """
    parse command line arguments and define options etc
    """
    usage = "usage: %prog [options] /path/to/database"
    optparser = OptionParser(usage, version=g2s.__version__)
    optparser.add_option("-a",
                         "--all-locations",
                         dest="all_locs",
                         default=False,
                         action="store_true",
                         help="Scan all points and reset location,\
not just unknown ones")

    (options, args) = optparser.parse_args()
    if len(args) != 1:
        optparser.error("Please enter a database path")
    dbpath = path.expanduser(args[0])

    return dbpath, options.all_locs


def main():
    """
    """
    starttime = datetime.now()

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

    dbpath, all_locs = parseargs()

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

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

    print("*" * 48)

    if all_locs is True:

        print("Resetting all trackpoints to location 1 (unknown)")
        g2s.reset_cities(cursor)

        print("Generating a list of trackpoints and cities to update")

    else:

        print("Generating a list with trackpoints with unknown "
              "cities to update.")

    locations_list = g2s.get_cityid_trackpoint_pairs(cursor, not all_locs)

    print("Updating {0} trackpoints".format(len(locations_list)))
    g2s.update_locations(cursor, locations_list)

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

    cursor.close()
    conn.commit()
    conn.close()

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

    endtime = datetime.now()
    print("Script took {0}".format(endtime - starttime))
    print("*" * 48)


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