# -*- coding: utf-8 -*-
"""
/***************************************************************************
 GraphabStyle
                                 A QGIS plugin
 This plugin allows you to convert easly a Graphab project
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2020-04-20
        git sha              : $Format:%H$
        copyright            : (C) 2020 by ThéMA
        email                : robin.marlinl@gmail.com
        author               : Robin Marlin-Lefebvre
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

import os # This is is needed in the pyqgis console also

from qgis.core import QgsFillSymbol, QgsLineSymbol

# Import to create tempory files
import tempfile


class GraphabStyle:
    """QGIS Plugin Implementation."""

    def __init__(self, plugin):
        # Link the object to the main object (GraphabPlugin) for shared variables
        self.plugin = plugin

    #--------------------------------------------------------------------------
    
    def prepareStyle(self, fieldname, layer, styleName, minScale = None, maxScale = None, sizeCapacity = True):
        """Edit pre-created symbology files with parameters choose by the user to change the 
        symbology of a choosen Graph. The symbology file created is not saved because it use temporaly 
        files."""

        # get path of style file
        _input = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'styles', styleName + '.qml')

        #read input file
        with open(_input, "rt") as fin:
            #read file contents to string
            data = fin.read()

            # get the field of a layer with his name
            idx = layer.fields().indexFromName(fieldname)
            # get min and max of the field wanted
            min = layer.minimumValue(idx)
            max = layer.maximumValue(idx)
            
            # avoid having a display problem because the min and max are identical
            if min >= max:
                min = 0
            
            if maxScale == None or int(maxScale) <= 1:
                maxScale = 15
                
            if minScale == None or int(minScale) >= int(maxScale) or int(minScale) < 0:
                minScale = 1
                
            #if the checkbox is checked : the size of centroid is based on the Capacity
            #else it's based on the current fieldname choose by the user
            if sizeCapacity:
                sizeFieldname = 'Capacity'
            else:
                sizeFieldname = fieldname
                
            # get the field of a layer with his name
            idx=layer.fields().indexFromName(sizeFieldname)
            
            # get min and max of the field wanted
            sizeValueMin = layer.minimumValue(idx)
            sizeValueMax = layer.maximumValue(idx)
            
            # avoid having a display problem because the min and max are identical
            if sizeValueMin >= sizeValueMax:
                sizeValueMin = 0
            
            #replace all occurrences of the required string
            for i in range(0,7):
                data = data.replace('@VAL'+str(i)+'@', str(min+i*(max-min)/6))

            data = data.replace('@MINIMUM2@', str(sizeValueMin))
            data = data.replace('@MAXIMUM2@', str(sizeValueMax))
            data = data.replace('@FIELDNAME1@', fieldname)
            data = data.replace('@FIELDNAME2@', sizeFieldname)
            data = data.replace('@MINSCALE@', str(minScale))
            data = data.replace('@MAXSCALE@', str(maxScale))
            #close the input file
            fin.close()
            #open the a temporary output file in write and read mode
            _output = tempfile.NamedTemporaryFile(mode = 'w+', dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'styles'), prefix = 'temp', suffix = '.qml', delete = False)
            #overrite the output file with the resulting data
            _output.write(data)
            #close the file
            _output.close()
            
            #load the syle file
            self.loadStyle(layer, _output.name)
            
            #remove temporary file
            os.remove(_output.name)
    
    #--------------------------------------------------------------------------
    
    def loadStyle(self, layer, styleFile):
        """Change the symbology of a layer with a pre-created symbology file"""

        layer.loadNamedStyle(os.path.realpath(styleFile))
            
        # refresh
        layer.triggerRepaint()
        self.plugin.iface.layerTreeView().refreshLayerSymbology(layer.id())
    
    #--------------------------------------------------------------------------
    
    def colorizeLine(self, layer, color):
        """Change color of the layer with the color asked. 
        This function works only with layer which represents lines."""
        
        # create a new symbol
        symbol = QgsLineSymbol.createSimple({'line_style': 'solid', 'color': color})
         
        # apply symbol to layer renderer
        layer.renderer().setSymbol(symbol)
         
        # repaint the layer
        layer.triggerRepaint()
        self.plugin.iface.layerTreeView().refreshLayerSymbology(layer.id())
    
    #--------------------------------------------------------------------------
    
    def colorizeFill(self, layer, color):
        """Change color of the layer with the color asked.
        This function works only with layer which represents things like circle or square"""
        
        # create a new symbol
        symbol = QgsFillSymbol.createSimple({'line_style': 'solid', 'color': color})
         
        # apply symbol to layer renderer
        layer.renderer().setSymbol(symbol)
         
        # repaint the layer
        layer.triggerRepaint()
        self.plugin.iface.layerTreeView().refreshLayerSymbology(layer.id())