# -*- coding: utf-8 -*-

from pygimli.gui.mpl import AppResourceMPL
from pygimli.importexport import readGPX, readSimpleLatLon
from pygimli.mplviewer import underlayMap
from pygimli.utils import opt_import

pyproj = opt_import('pyproj', 'coordinate transformations of EM data')


def findUTMZone(lon, lat):
    """
    find utm zone for lon and lat values.

    Return str(zone)+hemisphere
    lon -180 -- -174 -> 1 ... 174 -- 180 -> 60
    lat < 0 hemisphere = S, > 0 hemisphere = N
    """
    zone = (int(lon) + 180) / 6 + 1

    if lat > 0:
        return str(zone) + 'N'
    else:
        return str(zone) + 'S'

# def findUTMZone(...)


class GPSViewerApp(AppResourceMPL):

    """
    Main Class for GPS Viewer App.

    Default render window is a wxmpl panel
    """

    def __init__(self, parent, rendererSlot, propertyInspectorSlot):
        AppResourceMPL.__init__(self, parent,
                                rendererSlot,
                                propertyInspectorSlot)

        # set the name of this application that appears to the resource tree
        self.setName("GPS Viewer")

        # optionaly load content informations for this application,
        # generated by an gui-builder that wrote xrc-files
        # eg. wxFormBuilder, __file__ is needed to find the xrc-file
        self.loadXRC('gpsview.xrc', __file__)

        # register a menu to the main-MenuBar,
        # using this function ensures that this menu will be shown/hiden
        # respective to the activate status of the application
        self.mbCoordinatesMenu = self.createMainMenu('&Coordinates')

        # create an item to the Coordinates menu
        self.createMenuItem(self.mbCoordinatesMenu,
                            name="Import File",
                            help='auto',
                            function=self.onImportFile)

        self.createMenuItem(self.mbCoordinatesMenu,
                            name="Export ASCII",
                            help='auto',
                            function=self.onExportAscii)

        # create another item to the Coordinates menu
        self.createMenuItem(self.mbCoordinatesMenu,
                            name="Export UTM",
                            help='auto',
                            function=self.onExportUTM)

        # the application has some properties that can be altered by the
        # property inspector (PI), loaded and saved
        # self.titleTextProp = self.appendProperty(
        #     "Title", default='unknown', valType=str)

        self.vendorProp = self.appendProperty("MapVendor",
                                              valType=str,
                                              default='Google Maps')

        # self.vendorProp = self.appendProperty("MapVendor",
        # valType = unicode, default = 'Open Street Map')
        self.utmZone = self.appendProperty("UTMZone",
                                           valType=str,
                                           default='')

        self.ellipsoid = self.appendProperty("Ellipsoid",
                                             valType=str,
                                             default='WGS84')

        # define local data after your needs
        self.gpsWPTs = None
        self.newXLimits = None
        self.newYLimits = None

    def createPropertyPanel(self, parent):
        """
         Define and return panel that is shown in the property-inspector (PI)
         The panel will post created at the first call '
        """

        # create a Notebook for the PI and add the content for the panel with
        # the name piGPSViewerApp defined in gpsview.xrc
        panel = self.createPropertyInspectorNoteBookPanel(parent,
                                                          'piGPSViewerApp',
                                                          title='GPS Viewer')

        # bind properties on controls and targetfunctions
        # self.vendorProp.setCtrl(ctrl = wx.xrc.XRCCTRL(
        #     panel, 'gpsViewerVendorRadioBox')
        # , ctrlEvent = wx.EVT_RADIOBOX
        # , targetFunct = self.draw)

        # self.utmZone.setCtrl(ctrl = wx.xrc.XRCCTRL(
        #     panel, 'gpsViewerUTMZone')
        # , ctrlEvent = wx.EVT_KILL_FOCUS
        # , targetFunct = self.draw)
        # self.ellipsoid.setCtrl(ctrl = wx.xrc.XRCCTRL(
        #      panel, 'gpsViewerEllipsoid')
        # , ctrlEvent = wx.EVT_KILL_FOCUS
        # , targetFunct = self.draw)

        return panel

    def onZoomChanged(self):
        self.newXLimits = self.axes.get_xlim()
        self.newYLimits = self.axes.get_ylim()
        self.draw()

    def onPanChanged(self):
        self.newXLimits = self.axes.get_xlim()
        self.newYLimits = self.axes.get_ylim()
        self.draw()

    def drawData_(self):
        """Define what we have to be drawn (needed from base class) is called
        while a draw event is fired."""

        proj = self.getProjection()

        for p in self.gpsWPTs:
            x, y = proj(p[0], p[1])
            self.axes.plot(x, y, 'x', markersize=12, color='blue')
            self.axes.text(x, y, p[2])

        if self.newXLimits is not None:
            self.axes.set_xlim(self.newXLimits)
            self.axes.set_ylim(self.newYLimits)

        underlayMap(self.axes, proj,
                    vendor=self.vendorProp(),
                    zoom=-1, pixelLimit=[1500, 1024], verbose=True)

        self.axes.grid()

    def getProjection(self):
        """Create and return the current projection."""

#        hemisphere = 'north'
#        false_easting = 500000
#        false_northing = 0
#        if self.utmZone().find('S'):
#            hemisphere = 'south'
#            false_easting = 0
#            false_northing = 10000000

        # return pyproj.Proj(proj='utm', zone=self.utmZone(), ellps='WGS84')
        # Ell: GRS80, clrk66
        print("ell:", self.ellipsoid())
        if pyproj is None:
            return pyproj.Proj(proj='utm', zone=self.utmZone(),
                               ellps=self.ellipsoid())

    def openFile(self, files=None):
        """Load data here."""

        print(files.find('.gpx'))
        if files.find('.gpx') != -1:
            self.gpsWPTs = readGPX(files)
        else:
            self.gpsWPTs = readSimpleLatLon(files)

        print("reading ", len(self.gpsWPTs), " points")

        self.utmZone.setVal(
            findUTMZone(
                self.gpsWPTs[0][0],
                self.gpsWPTs[0][1]))
        self.draw()

    def onImportFile(self, event=None):
        """Import coordinates in Lon Lat format."""
        self.parent.onOpenFileDialog()

    def onExportUTM(self, event=None):
        """Export coordinates in UTM format."""
        pass

    def onExportAscii(self, event=None):
        """Export LonLat coordinates in simple column separated list."""

        fi = open("latlon.lanlot", 'w')
        for pnt in self.gpsWPTs:
            fi.write("%s\t%.8f\t%.8f\n" % (pnt[2], pnt[1], pnt[0]))

        fi.close()
