# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtCore, QtGui
from qgis.core import *
from qgis.gui import *
import const
import math

def deleteAllFeature(layer):
    try:
        for feat in layer.getFeatures():
            layer.deleteFeature(feat.id())
    except:
        pass

def deleteAllFeatureWithCommit(layer):
    try:
        layer.startEditing()

        deleteAllFeature(layer)

        layer.updateExtents()
        layer.commitChanges()
        layer.triggerRepaint()

    except:
        pass

def deleteToolLayer():
    try:
        root = QgsProject.instance().layerTreeRoot()
        for child in root.children():
            if child.name() == const.TEMP_GROUP_NAME:
                child.removeAllChildren()
                root.removeChildNode(child)
    except:
        pass

def copyFeature(fromLayer, toLayer):
    toLayer.startEditing()

    #コピー先クリアー
    deleteAllFeature(toLayer)

    #Featureコピー
    for feat in fromLayer.getFeatures():
        toLayer.dataProvider().addFeatures( [feat] )


    toLayer.updateExtents()
    toLayer.commitChanges()
    toLayer.triggerRepaint()

def getLayerByName(iface,name):
    try:
        legend = iface.legendInterface()
        for lyr in legend.layers():
            if lyr.name() == name:
                return lyr
    except:
        pass

def getFeatureById(layer, fid):
    features = layer.getFeatures()
    for feature in features:
        if feature.id() == fid:
            return feature

#標高を取得する
#引数　p:呼び出し元self pos:ポジション
#戻り値　float　ただし取得できなかった場合false
def getHyoko(p, pos):
    hyokoLyr = getLayerByName(p.iface, u"標高データ")
    ident = hyokoLyr.dataProvider().identify(QgsPoint(p.thisMapTool.toMapCoordinates(pos)), QgsRaster.IdentifyFormatValue)
    if ident.isValid():
        return ident.results()[1]

    else:
        return False

#値をQtのオブジェクトに指定されたフォーマットで出力する
def setText(qBox, val, fmt):
    qBox.setText(textFormat(val, fmt))

def textFormat(val, fmt):
    if type(val) is QPyNullVariant:
        return ""

    if val=="":
        return ""

    if fmt=="int":
        #整数
        return "%d" % val
    elif fmt=="flt":
        #小数そのまま
        return "%f" % val
    elif fmt=="intComma":
        #整数（カンマ区切り）
        return "{:,d}".format(val)
    elif fmt=="flt0":
        #小数点0桁
        temp = int(round(val))
        return "%d" % temp
    elif fmt=="flt1":
        #小数点1桁（カンマ区切り）
        temp = round(val * 10) / 10
        return "{:,.1f}".format(temp)
    elif fmt=="flt2":
        #小数点2桁（カンマ区切り）
        temp = round(val * 100) / 100
        return "{:,.2f}".format(temp)
    elif fmt=="flt3":
        #小数点3桁（カンマ区切り）
        temp = round(val * 1000) / 1000
        return "{:,.3f}".format(temp)
    elif fmt=="str":
        #文字列
        return val
    elif fmt=="p_intComma":
        #印刷用　整数（カンマ区切り）
        temp = val.replace(",","")
        return "{:10,d}".format(int(temp))

    elif fmt=="p_intComma2":
        return "{:10,d}".format(int(val))

    elif fmt=="p_flt1":
        #印刷用　小数点1桁（カンマ区切り）
        temp = val.replace(",","")
        return "{:10,.1f}".format(float(temp))

    elif fmt=="p_flt2":
        #印刷用　小数点2桁（カンマ区切り）
        temp = val.replace(",","")
        return "{:10,.2f}".format(float(temp))

    elif fmt=="p_flt3":
        #印刷用　小数点1桁（カンマ区切り）
        temp = val.replace(",","")
        return "{:10,.3f}".format(float(temp))

#距離(km)を計算する
#戻り値　float
def calcM(ln1, lt1, ln2, lt2):
    lon1, lat1, lon2, lat2 = map(math.radians, [ln1, lt1, ln2, lt2])
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
    c = 2 * math.asin(math.sqrt(a))
    m = const.R_VAL * c * 1000

    #print "calcKm: %f %f %f %f => %f" % (ln1, lt1, ln2, lt2, m)

    return m
