# -*- coding: utf-8 -*-
"""
/***************************************************************************
 StaraMapsDialog
                                 A QGIS plugin
 Test
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2023-05-05
        git sha              : $Format:%H$
        copyright            : (C) 2023 by Tarik
        email                : t@q
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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
import pathlib
import sys

import requests
from PyQt5.QtCore import QAbstractAnimation, QPropertyAnimation, QSequentialAnimationGroup, QSize, \
    QEasingCurve, Qt, \
    QPoint, pyqtSlot, pyqtSignal
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QFileDialog, QApplication, QGraphicsDropShadowEffect, QGraphicsOpacityEffect
from qgis.PyQt import QtWidgets
from qgis.PyQt import uic
from qgis.core import QgsRasterLayer
from qgis.utils import iface

from .File_widget import FileWidget
from .Form_widget import FormWidget
from .PointMapImport import PointMap
from .loading import Loading
from .qgisFuncs import print_log, VRCTOSHP, LOGTOSHP, KMLTOSHP, upgrade_grid, remove_file

# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
sys.path.append(os.path.dirname(__file__))
FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'ui/StaraMaps_dialog_base.ui'), resource_suffix='')


class StaraMapsDialog(QtWidgets.QDialog, FORM_CLASS):
    terrain_layer = pyqtSignal(object, bool)

    def __init__(self, layers=[], iface=None, project=None, parent=None):
        super(StaraMapsDialog, self).__init__(parent)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.setupUi(self)




        # idiomas
        self.label.setText(self.tr('Arraste e solte o arquivo'))
        self.label_2.setText(self.tr('ou'))
        self.pushButton.setText(self.tr('Carregar'))

        self.iface = iface
        self.lay = layers
        self.project = project
        try:
            self.project.layersAdded.disconnect()
        except Exception as e:
            self.iface.messageBar().pushWarning(e)

        try:
            self.project.layersRemoved.disconnect()
        except Exception as e:
            self.iface.messageBar().pushWarning(e)

        self.project.layersAdded.connect(self.addSignalFromQGis)
        self.project.layersRemoved.connect(self.delete_signal_from_qgis)
        self.pushButton_map.clicked.connect(self.terrain_state)


        self.pushButtonBack.hide()

        effect = QGraphicsDropShadowEffect()
        effect.setBlurRadius(5.0)
        effect.setColor(QColor(0, 0, 0, 80))
        effect.setOffset(1.0)
        self.frame_main_window.setGraphicsEffect(effect)

        self.dragPos = QPoint()
        self.lastItemsSelected = []

        self.pushButtonClose.clicked.connect(self.close)
        self.frame_7.setMaximumWidth(0)
        QApplication.processEvents()

        self.listWidget.setStyleSheet(self.listWidget.styleSheet())
        self.listWidget.itemSelectionChanged.connect(self.selectListWidgetItem)
        self.listWidget.focusOutEvent = self.listWidgetFocusOutEvent
        self.listWidget.itemClicked.connect(self.on_item_clicked)

        listEffect = QGraphicsOpacityEffect()
        listEffect.setOpacity(0.1)
        self.listWidget.setGraphicsEffect(listEffect)

        self.listWidget.graphicsEffect().setEnabled(False)

        self.pushButton.clicked.connect(self.open_file_name_dialog)
        self.pushButtonBack.clicked.connect(self.backAnimation)

        self.frame_6.dragEnterEvent = self.frame_6_drag_enter_event
        self.frame_6.dragLeaveEvent = self.frame_6_drag_leave_event
        self.frame_6.dropEvent = self.frame_6_drop_event

        self.frame_9.moveEvent = self.moveForm

        if self.lay:
            for layer in self.lay:
                item = QtWidgets.QListWidgetItem()
                file = FileWidget(item=item,
                                  path=layer.dataProvider().dataSourceUri(),
                                  project=self.project,
                                  iface=self.iface,
                                  layer_exist=layer)
                # file.terrain_signal.connect(self.terrain_layer.emit)
                file.optionsSignal.connect(self.openItemOnQGis)
                item.setSizeHint(QSize(394, 80))
                self.listWidget.addItem(item)
                self.listWidget.setItemWidget(item, file)

            self.checkhavefiles()

    def check_osm_exist(self):
        layer_name = "OSM"
        layer = next((layer for layer in self.project.mapLayers().values() if layer.name() == layer_name), None)
        if layer:
            return layer
        return None

    def remove_osm_layer(self):
        layer_name = "OSM"
        all_layers = list(self.project.mapLayers().values())
        for layer in all_layers:
            if layer.name() == layer_name:
                self.project.removeMapLayer(layer.id())

    def layers_overlay(self, active_layer):
        layers_o = []
        layers = list(self.project.mapLayers().values())
        for i, layer in enumerate(layers):
            if layer.extent().intersects(active_layer.extent()) and (
                    layer.name() != "OSM" and active_layer.name() != "OSM"):
                node = self.project.layerTreeRoot().findLayer(layer.id())

                if node.itemVisibilityChecked():
                    if not layer in layers_o:
                        layers_o.append(layer)

                node = self.project.layerTreeRoot().findLayer(active_layer.id())
                if node.itemVisibilityChecked():
                    if not active_layer in layers_o:
                        layers_o.append(active_layer)

        return layers_o

    def all_visible_layers(self):
        layers_v = []
        layers = list(self.project.mapLayers().values())
        for i, layer in enumerate(layers):
            if layer.name() != "OSM":
                node = self.project.layerTreeRoot().findLayer(layer.id())
                if node.itemVisibilityChecked():
                    layers_v.append(layer)

        return layers_v

    def terrain_state(self) -> None:

        if self.check_osm_exist():
            self.remove_osm_layer()
            self.iface.mapCanvas().setLayers([self.iface.activeLayer()])
            self.iface.mapCanvas().refresh()
            self.iface.mapCanvas().setDestinationCrs(self.iface.activeLayer().crs())
            canvas = iface.mapCanvas()
            extent = self.iface.activeLayer().extent()
            canvas.setExtent(extent)
            canvas.refresh()
            return

        all_layers = self.all_visible_layers()

        service_uri = "type=xyz&zmin=0&zmax=20&url=https://" + requests.utils.quote(
            "mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}")
        terrain_layer = QgsRasterLayer(service_uri, 'OSM', 'wms')

        if not terrain_layer.isValid():
            print("Erro ao carregar a camada de terreno XYZ.")
        else:

            if not self.iface.activeLayer():
                self.iface.messageBar().pushWarning(self.tr("Aviso"), self.tr("Nenhuma Layer Selecionada."))
                return
            self.project.addMapLayer(terrain_layer, False)
            self.iface.mapCanvas().setLayers(all_layers + [terrain_layer])
            terrain_layer.renderer().setOpacity(1)
            terrain_layer.triggerRepaint()

            self.iface.mapCanvas().refresh()
            self.iface.mapCanvas().setDestinationCrs(self.iface.activeLayer().crs())

        canvas = iface.mapCanvas()
        extent = self.iface.activeLayer().extent()
        canvas.setExtent(extent)
        canvas.refresh()

    def delete_signal_from_qgis(self, layers):
        for layer_id in layers:
            items = [self.listWidget.item(x) for x in range(self.listWidget.count())]
            for item in items:
                widget = self.listWidget.itemWidget(item)
                if widget.layer_id == layer_id:
                    layer_name = widget.filename
                    with_signal = widget.remove_with_signal
                    widget.deleteLater()
                    index = self.listWidget.indexFromItem(item).row()
                    item_from_list = self.listWidget.takeItem(index)
                    del item_from_list
                    self.checkhavefiles('delete')
                    print(f"{widget.layer_id} {layer_id} Deleted.")
                    if with_signal:
                        directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'backup', layer_name)
                        remove_file(directory + '.shp')
                        remove_file(directory + '.cpg')
                        remove_file(directory + '.dbf')
                        remove_file(directory + '.prj')
                        remove_file(directory + '.shx')
                    break

        items = [self.listWidget.item(x) for x in range(self.listWidget.count())]

        if len(items) > 0:
            active_item_after_delete = self.listWidget.itemWidget(items[-1])
            canvas = self.iface.mapCanvas()
            extent = active_item_after_delete.layer.extent()
            canvas.setExtent(extent)
            canvas.refresh()

    def addSignalFromQGis(self, layers):
        for layer_id in layers:
            items = [self.listWidget.item(x) for x in range(self.listWidget.count())]
            for item in items:
                widget = self.listWidget.itemWidget(item)
                if widget.layer_id == layer_id:
                    print(f"{widget.layer_id} {layer_id} added.")

    def mousePressEvent(self, event):
        self.dragPos = event.globalPos()

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            self.move(self.pos() + event.globalPos() - self.dragPos)
            self.dragPos = event.globalPos()
            event.accept()

    @pyqtSlot(object)
    def openItemOnQGis(self, widget):
        widget.checkBox.setEnabled(True)
        canvas = iface.mapCanvas()
        extent = widget.layer.extent()
        canvas.setExtent(extent)
        canvas.refresh()

        self.doAnimation(widget)

    def backAnimation(self):
        self.fo.close()
        self.sequentialTemp.disconnect()
        self.sequentialTemp.setDirection(QAbstractAnimation.Backward)
        self.widAnim1.setDirection(QAbstractAnimation.Backward)
        self.widAnim1.disconnect()
        self.widAnim1.finished.connect(lambda: self.stackedWidget.setCurrentIndex(0))
        self.sequentialTemp.start()
        self.sequentialTemp.finished.connect(self.pushButtonBack.hide)
        self.sequentialTemp.finished.connect(self.tempWidget.deleteLater)
        self.sequentialTemp.finished.connect(self.widAnim1.start)
        self.sequentialTemp.finished.connect(self.fo.deleteLater)

    def doAnimation(self, widget):

        self.tempWidget = FileWidget(widget.item,
                                     widget.path,
                                     self.project,
                                     temp=True,
                                     layer_exist=widget.layer,
                                     parent=self.stackedWidget.widget(1))

        self.tempWidget.frame_3.setStyleSheet(
            '''
                #frame_3{
                    background-color:transparent;
                    border: none;
                }
            '''
        )
        self.tempWidget.pushButtonOptions.close()
        self.tempWidget.valueComboBox.setEnabled(False)
        offset = 30
        self.tempWidget.setMaximumSize(QSize(self.tempWidget.width() - offset, self.tempWidget.height()))
        self.tempWidget.setMinimumSize(QSize(self.tempWidget.width() - offset, self.tempWidget.height()))
        self.tempWidget.hide()
        self.tempWidget.move(QPoint(int(self.stackedWidget.widget(1).width()),
                                    self.tempWidget.pos().y()))
        effect = QGraphicsDropShadowEffect()
        effect.setBlurRadius(5.0)
        effect.setColor(QColor(0, 0, 0, 80))
        effect.setOffset(1.0)
        self.tempWidget.setGraphicsEffect(effect)

        self.stackedWidget.setCurrentIndex(1)

        self.widAnim1 = QPropertyAnimation(self.frame_main_window, b"maximumSize")
        self.widAnim1.setEasingCurve(QEasingCurve.InOutCubic)
        startValue = self.size()
        endValue = QSize(400, startValue.height())
        self.widAnim1.setStartValue(startValue)
        self.widAnim1.setEndValue(endValue)
        self.widAnim1.setDuration(200)
        self.widAnim1.setDirection(QAbstractAnimation.Forward)
        self.widAnim1.finished.connect(lambda: self.doAnimationFinished(self.tempWidget, widget))
        self.widAnim1.start()

    @pyqtSlot()
    def doAnimationFinished(self, temp_widget, original_widget):
        page_width = self.stackedWidget.widget(1).width()
        page_height = self.stackedWidget.widget(1).height()
        centerx = int(page_width / 2 - temp_widget.width() / 2)

        x_offset = 25
        y_offset = 10

        self.pushButtonBack.move(page_width - 32 - x_offset,
                                 page_height - 32 - y_offset)
        self.pushButtonBack.show()
        eff = QGraphicsOpacityEffect()
        eff.setOpacity(0.0)
        self.pushButtonBack.setGraphicsEffect(eff)

        temp_widget.show()
        self.temAnim1 = QPropertyAnimation(temp_widget, b"pos")
        self.temAnim1.setEasingCurve(QEasingCurve.InOutCubic)
        startValue1 = temp_widget.pos()
        endValue1 = QPoint(centerx, temp_widget.pos().y())
        self.temAnim1.setStartValue(startValue1)
        self.temAnim1.setEndValue(endValue1)
        self.temAnim1.setDuration(100)

        self.temAnim2 = QPropertyAnimation(temp_widget, b"pos")
        self.temAnim2.setEasingCurve(QEasingCurve.InOutCubic)
        startValue2 = endValue1
        endValue2 = QPoint(centerx, temp_widget.pos().y() + 10)
        self.temAnim2.setStartValue(startValue2)
        self.temAnim2.setEndValue(endValue2)
        self.temAnim2.setDuration(200)

        self.sequentialTemp = QSequentialAnimationGroup()
        self.sequentialTemp.addAnimation(self.temAnim1)
        self.sequentialTemp.addAnimation(self.temAnim2)
        # self.sequentialTemp.finished.connect(lambda: self.pushButtonBack.graphicsEffect.setEnable())
        self.sequentialTemp.finished.connect(lambda: self.show_file_options(original_widget))
        self.sequentialTemp.setDirection(QAbstractAnimation.Forward)
        self.sequentialTemp.start()

        self.buttonBackShowAnim = QPropertyAnimation(eff, b"opacity")
        self.buttonBackShowAnim.setStartValue(0.0)
        self.buttonBackShowAnim.setEndValue(1.0)
        self.buttonBackShowAnim.setDuration(1000)
        self.buttonBackShowAnim.finished.connect(lambda: self.pushButtonBack.graphicsEffect().setEnabled(False))
        self.buttonBackShowAnim.start()

    @pyqtSlot()
    def show_file_options(self, file_widget):
        from .File_options import FileOptions

        file_widget.bring_to_front()
        page_width = self.stackedWidget.widget(1).width()

        y_wl = file_widget.rect().height() + 20
        y_button = self.pushButtonBack.pos().y() - 20

        max_file_options_width = self.stackedWidget.widget(1).rect().width() - 40
        max_file_options_height = y_button - y_wl

        itens = [self.listWidget.item(x) for x in range(self.listWidget.count())]

        wid_itens = [self.listWidget.itemWidget(item) for item in itens]
        self.fo = FileOptions(file_widget,
                              self.project,
                              self.iface,
                              wid_itens,
                              self,
                              parent=self.stackedWidget.widget(1))
        ''' Apenas habilitar unir mapas se houver mais de um mapa importado'''
        if len(itens) < 2:
            self.fo.pushButtonumaps.setEnabled(False)
        self.fo.reset_layer_signal.connect(self.add_replace_layer)
        self.fo.merged_layer_signal.connect(self.add_merged_layer)
        self.fo.back_button_hide_signal.connect(self.pushButtonBack.hide)
        self.fo.back_button_show_signal.connect(self.pushButtonBack.show)
        self.fo.back_animation_signal.connect(self.backAnimation)
        self.fo.resize(max_file_options_width, max_file_options_height)

        centerx = int(page_width / 2 - self.fo.width() / 2)
        self.fo.move(centerx, y_wl)
        # self.fo.resize()

        self.fo.show()

    @pyqtSlot(str, list)
    def add_merged_layer(self, path, tree):

        item = QtWidgets.QListWidgetItem()
        file = FileWidget(item=item,
                          path=path,
                          project=self.project,
                          iface=self.iface
                          )
        file.optionsSignal.connect(self.openItemOnQGis)
        item.setSizeHint(QSize(394, 80))
        self.listWidget.addItem(item)
        self.listWidget.setItemWidget(item, file)

        self.checkhavefiles()
        file.addLayerOnQGis(tree)

    @pyqtSlot(object, list)
    def add_replace_layer(self, layer, tree):
        layer_path = layer.dataProvider().dataSourceUri()
        item = QtWidgets.QListWidgetItem()
        file = FileWidget(item=item,
                          path=layer_path,
                          project=self.project,
                          iface=self.iface,
                          layer_exist=layer)
        file.optionsSignal.connect(self.openItemOnQGis)
        item.setSizeHint(QSize(394, 80))

        self.listWidget.addItem(item)
        self.listWidget.setItemWidget(item, file)

        self.checkhavefiles()
        file.addLayerOnQGis(tree)
        upgrade_grid(layer, self.iface)

    def add_new_file_to_list_widget(self, path, file_extension=False):

        item = QtWidgets.QListWidgetItem()
        file = FileWidget(item, path, self.project, iface=self.iface, file_extencion=file_extension)

        item.setSizeHint(QSize(394, 80))
        file.optionsSignal.connect(self.openItemOnQGis)
        # Criar FileWidget temporário
        self.fileTemp = FileWidget(item, path, self.project, temp=True, parent=self.frame_7)
        self.fileTemp.move(self.frame_7.rect().x(), int(self.frame_7.height() / 2 - self.fileTemp.height() / 2))
        self.fileTemp.pushButtonOptions.close()

        effectFileTemp = QGraphicsDropShadowEffect()
        effectFileTemp.setBlurRadius(5.0)
        effectFileTemp.setColor(QColor(0, 0, 0, 80))
        effectFileTemp.setOffset(1.0)
        self.fileTemp.setGraphicsEffect(effectFileTemp)

        self.fileTemp.frame_3.setStyleSheet(
            '''
                #frame_3{
                    background-color:transparent;
                    border: none;
                }
            '''
        )
        self.fileTemp.valueComboBox.setEnabled(False)
        if self.listWidget.count() > 0:
            self.fileTemp.show()
        self.fileTemp.do_animation_form_loop()

        self.form = FormWidget(item, file, self.project, parent=self.stackedWidget.widget(0))
        self.form.move(self.frame_9.pos())
        self.form.addSignal.connect(self.add_file_after_form)
        self.form.cancelSignal.connect(self.cancel_add_file)
        self.form.show()

        self.listWidget.graphicsEffect().setEnabled(True)

    # Talvez não precisa
    def moveForm(self, event):
        if hasattr(self, 'form'):
            self.form.move(self.frame_9.pos())
        if hasattr(self, 'fileTemp'):
            self.fileTemp.move(self.frame_7.rect().x(), int(self.frame_7.height() / 2 - self.fileTemp.height() / 2))

    # Conectar sinal do self.form aqui
    @pyqtSlot(object, object, list)
    def add_file_after_form(self, item, file, list_groups):
        self.form.deleteLater()
        if self.form.anoRadioButton.isChecked():
            t_layer = 'a'  # ano
        else:
            t_layer = 'b'  # bordadura
            if self.form.lineRadioButton.isChecked():
                t_layer = 'l'  # lina
            # elif self.form.pointRadioButton.isChecked():
            # t_layer = 'p'

        del self.form

        self.fileTemp.deleteLater()
        del self.fileTemp
        print(f'{t_layer} added.dasdsdsad')
        file.addLayerOnQGis(list_groups=list_groups, layer_type=t_layer)
        self.listWidget.addItem(item)
        self.listWidget.setItemWidget(item, file)

        self.listWidget.graphicsEffect().setEnabled(False)

    @pyqtSlot()
    def cancel_add_file(self):

        self.form.deleteLater()
        del self.form

        self.fileTemp.deleteLater()
        del self.fileTemp

        self.checkhavefiles("delete")
        self.listWidget.graphicsEffect().setEnabled(False)

    def frame_6_drag_leave_event(self, event):
        self.sequential.stop()
        self.frame_8.move(QPoint(100, 80))

    def frame_6_drag_enter_event(self, event):
        if event.mimeData().hasUrls() and not hasattr(self, 'form'):
            if len(event.mimeData().urls()) == 1:
                for url in event.mimeData().urls():
                    if url.toLocalFile().endswith('.shp') or \
                            url.toLocalFile().endswith('.vrc') or \
                            url.toLocalFile().endswith('.txt') or \
                            url.toLocalFile().endswith('.dat') or \
                            url.toLocalFile().endswith('.csv') or \
                            url.toLocalFile().endswith('.log') or \
                            url.toLocalFile().endswith('.kml'):
                        event.acceptProposedAction()
                        self.drag_accept_animation()
                        return
        event.ignore()

    def drag_accept_animation(self):
        self.dragAnim = QPropertyAnimation(self.frame_8, b"pos")
        self.dragAnim.setEasingCurve(QEasingCurve.InOutCubic)
        self.dragAnim.setStartValue(QPoint(100, 80))
        self.dragAnim.setEndValue(QPoint(100, 40))
        self.dragAnim.setDuration(1000)

        self.dragAnim2 = QPropertyAnimation(self.frame_8, b"pos")
        self.dragAnim2.setEasingCurve(QEasingCurve.InOutCubic)
        self.dragAnim2.setStartValue(QPoint(100, 40))
        self.dragAnim2.setEndValue(QPoint(100, 80))
        self.dragAnim2.setDuration(1000)

        self.sequential = QSequentialAnimationGroup()
        self.sequential.addAnimation(self.dragAnim)
        self.sequential.addAnimation(self.dragAnim2)
        self.sequential.setLoopCount(-1)
        self.sequential.start()

    def frame_6_drop_event(self, event):

        files = [u.toLocalFile() for u in event.mimeData().urls()]

        for file in files:
            self.check_file_extension(file)

    def open_file_name_dialog(self):

        options = QFileDialog.Options()
        filename, _ = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "",
                                                  "Shape Files (*.shp *.vrc *.txt *.dat *.csv *.log *.kml)",
                                                  options=options)

        if filename:
            self.check_file_extension(filename)

        else:
            return

        self.checkhavefiles()

    def check_file_extension(self, file):
        file_extension = pathlib.Path(file).suffix
        items = [self.listWidget.item(x) for x in range(self.listWidget.count())]
        file_name = file.split('/')[-1]
        file_name_without_ext = file_name.split('.')[0]
        for item in items:
            widget = self.listWidget.itemWidget(item)
            if widget.labelFileName.text() == file_name_without_ext:
                widget.do_animation()
                if hasattr(self, 'sequential'):
                    self.sequential.stop()
                self.frame_8.move(QPoint(100, 80))
                return

        if file_extension == '.shp':
            self.add_new_file_to_list_widget(file)
            self.check_file_extension_finished()

        elif file_extension == '.vrc':
            original_path_split = file.split('/')
            file_name_with_ext = original_path_split.pop(-1)
            file_name = file_name_with_ext.split('.').pop(0)
            only_path = '/'.join(original_path_split)
            new_path = only_path + '/' + file_name + '.shp'

            self.loading_vrc_to_shp = Loading(self.frame_9)
            self.loading_vrc_to_shp.start()
            self.loading_vrc_to_shp.show()
            self.vrc_to_shp = VRCTOSHP(file, new_path)
            self.vrc_to_shp.on_finished.connect(self.loading_vrc_to_shp.stop)
            self.vrc_to_shp.on_finished.connect(self.loading_vrc_to_shp.hide)
            self.vrc_to_shp.on_finished.connect(self.loading_vrc_to_shp.deleteLater)
            self.vrc_to_shp.on_finished.connect(lambda: self.add_new_file_to_list_widget(new_path))
            self.vrc_to_shp.on_finished.connect(self.check_file_extension_finished)
            self.vrc_to_shp.start()

        elif file_extension == '.dat' or file_extension == '.txt' or file_extension == '.csv':

            original_path_split = file.split('/')
            file_name_with_ext = original_path_split.pop(-1)
            file_name = file_name_with_ext.split('.').pop(0)
            only_path = '/'.join(original_path_split)
            new_path = only_path + '/' + file_name + '.shp'

            self.p_m = PointMap(file, new_path, self.frame_6)
            self.p_m.cancel_signal.connect(lambda: (
                self.sequential.stop(),
                self.frame_8.move(QPoint(100, 80)),
                self.p_m.deleteLater()
            ))
            self.p_m.finish_signal.connect(lambda: (
                self.add_new_file_to_list_widget(new_path, True),
                self.check_file_extension_finished(),
                self.p_m.deleteLater()
            ))

            '''self.points_to_shp = DatTxtCsvToSHP(file)
            self.points_to_shp.on_finished.connect(self.loading_vrc_to_shp.stop)
            self.points_to_shp.on_finished.connect(self.loading_vrc_to_shp.hide)
            self.points_to_shp.on_finished.connect(self.loading_vrc_to_shp.deleteLater)'''

            '''self.points_to_shp.on_finished.connect(lambda: self.add_new_file_to_list_widget(new_path))
            self.points_to_shp.on_finished.connect(self.check_file_extention_finished)'''

            # self.points_to_shp.start()

        elif file_extension == '.log':
            original_path_split = file.split('/')
            file_name_with_ext = original_path_split.pop(-1)
            file_name = file_name_with_ext.split('.').pop(0)
            only_path = '/'.join(original_path_split)
            new_path_csv = only_path + '/' + file_name + '.csv'
            new_path_shp = only_path + '/' + file_name + '.shp'

            self.loading_vrc_to_shp = Loading(self.frame_9)
            self.loading_vrc_to_shp.start()
            self.loading_vrc_to_shp.show()

            self.log_to_shp = LOGTOSHP(file, new_path_csv)
            self.log_to_shp.on_finished.connect(self.loading_vrc_to_shp.stop)
            self.log_to_shp.on_finished.connect(self.loading_vrc_to_shp.hide)
            self.log_to_shp.on_finished.connect(self.loading_vrc_to_shp.deleteLater)
            self.log_to_shp.on_finished.connect(lambda: self.add_new_file_to_list_widget(new_path_shp))
            self.log_to_shp.on_finished.connect(self.check_file_extension_finished)
            self.log_to_shp.start()

        elif file_extension == '.kml':

            original_path_split = file.split('/')
            file_name_with_ext = original_path_split.pop(-1)
            file_name = file_name_with_ext.split('.').pop(0)
            only_path = '/'.join(original_path_split)
            new_path_shp = only_path + '/' + file_name + '.shp'

            self.loading_vrc_to_shp = Loading(self.frame_9)
            self.loading_vrc_to_shp.start()
            self.loading_vrc_to_shp.show()

            self.kml_to_shp = KMLTOSHP(file)
            self.kml_to_shp.on_finished.connect(self.loading_vrc_to_shp.stop)
            self.kml_to_shp.on_finished.connect(self.loading_vrc_to_shp.hide)
            self.kml_to_shp.on_finished.connect(self.loading_vrc_to_shp.deleteLater)
            self.kml_to_shp.on_finished.connect(lambda: self.add_new_file_to_list_widget(new_path_shp))
            self.kml_to_shp.on_finished.connect(self.check_file_extension_finished)
            self.kml_to_shp.start()

        else:
            print_log(self, self.check_file_extension, msg="Formato não suportado!")

    def check_file_extension_finished(self):
        self.checkhavefiles()
        if hasattr(self, 'sequential'):
            self.sequential.stop()
        self.frame_8.move(QPoint(100, 80))

    def checkhavefiles(self, t="add"):
        # pode ser que este método é chamado antes que a animação do form temine
        # por isso o count vem zerado por hora foi colocado < 2 porque quando vem dos arquivos existentes
        # o count vem == 1

        itens_count = self.listWidget.count()
        if (itens_count == 0 and t == 'add') or (itens_count > 0 and t == 'add'):
            self.anim = QPropertyAnimation(self.frame_7, b"maximumSize")
            self.anim.setEasingCurve(QEasingCurve.InOutCubic)
            self.anim.setStartValue(QSize(0, self.frame_7.height()))
            self.anim.setEndValue(QSize(515, self.frame_7.height()))
            self.anim.setDirection(QAbstractAnimation.Forward)
            if itens_count == 0 and t == 'add':
                self.anim.finished.connect(self.fileTemp.show)

        elif itens_count == 0 and t == 'delete':
            self.anim.setDirection(QAbstractAnimation.Backward)
            self.anim.finished.connect(self.anim.deleteLater)

        self.anim.start()

        # self.frame_7.setMaximumSize(QSize(515, self.frame_7.height()))

    def on_item_clicked(self, item):
        widget = self.listWidget.itemWidget(item)

        self.iface.setActiveLayer(widget.layer)
        ov_layers = self.layers_overlay(widget.layer)
        osm_layer = self.check_osm_exist()

        if widget.checkBox.isChecked():
            current_layers = [widget.layer, osm_layer]
        else:
            if osm_layer:
                current_layers = [osm_layer]
            else:
                current_layers = []

        self.iface.mapCanvas().setLayers(ov_layers + current_layers)
        self.iface.mapCanvas().setDestinationCrs(widget.layer.crs())
        self.iface.mapCanvas().refresh()

        canvas = iface.mapCanvas()
        extent = widget.layer.extent()
        canvas.setExtent(extent)
        canvas.refresh()

    def listWidgetFocusOutEvent(self, event):
        if self.lastItemsSelected:
            for item in self.lastItemsSelected:
                item.frame_3.setStyleSheet('''
                    #frame_3{
                        background-color:transparent;
                        border-bottom: 2px solid;
                        border-bottom-color: rgb(235, 235, 235);
                    }
                ''')

        self.lastItemsSelected.clear()

    @pyqtSlot()
    def selectListWidgetItem(self):

        if self.lastItemsSelected:
            for item in self.lastItemsSelected:
                item.frame_3.setStyleSheet('''
                    #frame_3{
                        background-color:transparent;
                        border-bottom: 2px solid;
                        border-bottom-color: rgb(235, 235, 235);
                    }
                ''')

            self.lastItemsSelected.clear()
        items = self.listWidget.selectedItems()
        for item in items:
            # index = self.listWidget.indexFromItem(item).row()
            widget = self.listWidget.itemWidget(item)
            widget.frame_3.setStyleSheet('''
                #frame_3{
                    background-color:transparent;
                    border-bottom: 2px solid;
                    border-bottom-color: rgb(243, 116, 53);
                }

            ''')
            self.lastItemsSelected.append(widget)

    def resizeEvent(self, event):
        pass
        '''if self.frame_7.width() != 0:
            self.frame_7lastWidth = self.frame_7.width()'''
