import os
import platform
import tempfile
import webbrowser
from qgis import processing
from PyQt5.QtCore import pyqtSignal, Qt, QCoreApplication, QUrl
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QApplication

from qgis._core import QgsSettings, Qgis, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsProject
from qgis._gui import QgsVertexMarker, QgsMapToolEmitPoint

from .cyanlove_transform_gps_to_gps import CoordinateConverter

epsg4326 = QgsCoordinateReferenceSystem('EPSG:4326')


class CopyLatLonTool(QgsMapToolEmitPoint):
    captureStopped = pyqtSignal()

    def __init__(self, iface):
        QgsMapToolEmitPoint.__init__(self, iface.mapCanvas())
        self.snapcolor = None
        self.iface = iface
        self.canvas = iface.mapCanvas()
        self.marker = None
        self.vertex = None
        qset = QgsSettings()
        self.capturePrefix = qset.value('/LatLonTools/CapturePrefix', '')
        self.captureSuffix = qset.value('/LatLonTools/CaptureSuffix', '')

    # 激活时，改为十字
    def activate(self):
        self.canvas.setCursor(Qt.CrossCursor)
        self.snapcolor = QgsSettings().value("/qgis/digitizing/snap_color", QColor(Qt.magenta))

    def deactivate(self):
        self.removeMarker()
        self.removeVertexMarker()
        self.captureStopped.emit()

    # 鼠标移动时，捕捉数据
    def canvasMoveEvent(self, event):

        pt = self.snappoint(event.originalPixelPoint())
        canvasCRS = self.canvas.mapSettings().destinationCrs()
        if canvasCRS != epsg4326:
            # 转换为格式
            transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
            pt4326 = transform.transform(pt.x(), pt.y())
        else:
            pt4326 = pt

        lon = pt4326.x()
        lat = pt4326.y()
        msg = '{}{}{}'.format(f"{lon:.6f}", ",", f"{lat:.6f}")
        try:
            if pt is None:
                self.iface.statusBarIface().showMessage("{} - {}".format(msg, 'Out of bounds'), 4000)
            else:
                self.iface.statusBarIface().showMessage("{}".format(msg), 4000)
        except Exception as e:
            self.iface.statusBarIface().showMessage(f"{str(e)}")

    def snappoint(self, qpoint):
        match = self.canvas.snappingUtils().snapToMap(qpoint)
        if match.isValid():
            if self.vertex is None:
                self.vertex = QgsVertexMarker(self.canvas)
                self.vertex.setIconSize(12)
                self.vertex.setPenWidth(2)
                self.vertex.setColor(self.snapcolor)
                self.vertex.setIconType(QgsVertexMarker.ICON_BOX)
            self.vertex.setCenter(match.point())
            return match.point()
        else:
            self.removeVertexMarker()
            return self.toMapCoordinates(qpoint)

    # 当鼠标按钮释放时，捕获坐标，格式化它，并将其复制到剪贴板。pt 是 QgsPointXY 类型
    def canvasReleaseEvent(self, event):

        pt = self.snappoint(event.originalPixelPoint())
        canvasCRS = self.canvas.mapSettings().destinationCrs()
        if canvasCRS != epsg4326:
            # 转换为4326格式
            transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
            pt4326 = transform.transform(pt.x(), pt.y())
        else:
            pt4326 = pt

        lon = pt4326.x()
        lat = pt4326.y()
        msg = '{}{}{}'.format(f"{lon:.6f}", ",", f"{lat:.6f}")
        self.removeVertexMarker()
        try:
            if msg is not None:
                clipboard = QApplication.clipboard()
                clipboard.setText(msg)
                print(QCoreApplication.translate('@default', 'copied to the clipboard'))
                self.iface.messageBar().pushMessage("", "{} {} {}".format('经纬度', msg,
                                                                          '已经复制到剪贴板'),
                                                    level=Qgis.Info, duration=3)
        except Exception as e:
            print(str(e))
            self.iface.messageBar().pushMessage("", "{} {}".format('无效的坐标:', e),
                                                level=Qgis.Warning, duration=3)

    def removeMarker(self):
        if self.marker is not None:
            self.canvas.scene().removeItem(self.marker)
            self.marker = None

    def removeVertexMarker(self):
        if self.vertex is not None:
            self.canvas.scene().removeItem(self.vertex)
            self.vertex = None


class ShowBaiduMapTool(QgsMapToolEmitPoint):
    captureStopped = pyqtSignal()

    def __init__(self, iface):
        QgsMapToolEmitPoint.__init__(self, iface.mapCanvas())
        self.snapcolor = None
        self.iface = iface
        self.canvas = iface.mapCanvas()
        self.marker = None
        self.vertex = None
        qset = QgsSettings()
        self.capturePrefix = qset.value('/LatLonTools/CapturePrefix', '')
        self.captureSuffix = qset.value('/LatLonTools/CaptureSuffix', '')

    # 激活时，改为十字
    def activate(self):
        self.canvas.setCursor(Qt.CrossCursor)
        self.snapcolor = QgsSettings().value("/qgis/digitizing/snap_color", QColor(Qt.magenta))

    def deactivate(self):
        self.removeMarker()
        self.removeVertexMarker()
        self.captureStopped.emit()

    def canvasPressEvent(self, event):
        pt = self.snappoint(event.originalPixelPoint())
        canvasCRS = self.canvas.mapSettings().destinationCrs()
        if canvasCRS != epsg4326:
            # 转换为格式
            transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
            pt4326 = transform.transform(pt.x(), pt.y())
        else:
            pt4326 = pt

        lon = pt4326.x()
        lat = pt4326.y()
        msg = '{}{}{}'.format(f"{lon:.6f}", ",", f"{lat:.6f}")
        try:
            if pt is None:
                self.iface.statusBarIface().showMessage("{} - {}".format(msg, 'Out of bounds'), 4000)
            else:
                # 转换
                lon, lat = CoordinateConverter.wgs84_to_bd09(lon, lat)
                url = QUrl(f'https://api.map.baidu.com/marker?location={lat},{lon}&zoom=12&output=html').toString()
                webbrowser.open(url, new=2)
        except Exception as e:
            self.iface.statusBarIface().showMessage(f"{str(e)}")

    # 鼠标移动时，捕捉数据
    def canvasMoveEvent(self, event):

        pt = self.snappoint(event.originalPixelPoint())
        canvasCRS = self.canvas.mapSettings().destinationCrs()
        if canvasCRS != epsg4326:
            # 转换为格式
            transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
            pt4326 = transform.transform(pt.x(), pt.y())
        else:
            pt4326 = pt

        lon = pt4326.x()
        lat = pt4326.y()
        msg = '{}{}{}'.format(f"{lon:.6f}", ",", f"{lat:.6f}")
        try:
            if pt is None:
                self.iface.statusBarIface().showMessage("{} - {}".format(msg, 'Out of bounds'), 4000)
            else:
                pass
        except Exception as e:
            self.iface.statusBarIface().showMessage(f"{str(e)}")

    def snappoint(self, qpoint):
        match = self.canvas.snappingUtils().snapToMap(qpoint)
        if match.isValid():
            if self.vertex is None:
                self.vertex = QgsVertexMarker(self.canvas)
                self.vertex.setIconSize(12)
                self.vertex.setPenWidth(2)
                self.vertex.setColor(self.snapcolor)
                self.vertex.setIconType(QgsVertexMarker.ICON_BOX)
            self.vertex.setCenter(match.point())
            return match.point()
        else:
            self.removeVertexMarker()
            return self.toMapCoordinates(qpoint)

    # 当鼠标按钮释放时，捕获坐标，格式化它，并将其复制到剪贴板。pt 是 QgsPointXY 类型
    def canvasReleaseEvent(self, event):

        pt = self.snappoint(event.originalPixelPoint())
        canvasCRS = self.canvas.mapSettings().destinationCrs()
        if canvasCRS != epsg4326:
            # 转换为4326格式
            transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
            pt4326 = transform.transform(pt.x(), pt.y())
        else:
            pt4326 = pt

        lon = pt4326.x()
        lat = pt4326.y()
        msg = '{}{}{}'.format(f"{lon:.6f}", ",", f"{lat:.6f}")
        self.removeVertexMarker()
        try:
            if msg is not None:
                clipboard = QApplication.clipboard()
                clipboard.setText(msg)
                print(QCoreApplication.translate('@default', 'copied to the clipboard'))
                self.iface.messageBar().pushMessage("", "{} {} {}".format('经纬度', msg,
                                                                          '已经复制到剪贴板'),
                                                    level=Qgis.Info, duration=3)
        except Exception as e:
            print(str(e))
            self.iface.messageBar().pushMessage("", "{} {}".format('无效的坐标:', e),
                                                level=Qgis.Warning, duration=3)

    def removeMarker(self):
        if self.marker is not None:
            self.canvas.scene().removeItem(self.marker)
            self.marker = None

    def removeVertexMarker(self):
        if self.vertex is not None:
            self.canvas.scene().removeItem(self.vertex)
            self.vertex = None
