# -*- coding: utf-8 -*-
"""
/***************************************************************************
 ConverterDockWidget
                                 A QGIS plugin
 Tool to convert spatialite 3 or 4 into 5
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2021-08-27
        git sha              : $Format:%H$
        copyright            : (C) 2021 by adArte srl
        email                : enzo.zo.ccc@gmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 subprocess
import platform
from qgis.PyQt import uic
from qgis.PyQt.QtGui import QDesktopServices
from qgis.PyQt.QtCore import  pyqtSlot, pyqtSignal,QThread,QUrl,QSettings,Qt
from qgis.PyQt.QtWidgets import QApplication, QDialog, QMessageBox, QFileDialog,QLineEdit,QWidget,QCheckBox
from qgis.PyQt.QtSql import *
from qgis.PyQt.uic import loadUiType
from qgis.PyQt import  QtWidgets 
from qgis.core import  *
from qgis.gui import  *
from qgis.utils import iface
from qgis.core import QgsApplication

FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'spatialite_converter_dockwidget_base.ui'))


class ConverterDockWidget(QtWidgets.QDockWidget, FORM_CLASS):

    closingPlugin = pyqtSignal()

    def __init__(self, parent=None):
        """Constructor."""
        super(ConverterDockWidget, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://doc.qt.io/qt-5/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        self.test()
    def test(self):    
        
        p = QgsProviderRegistry.instance().providerMetadata('spatialite')
        
        a=self.comboBox_listdb.addItems(p.connections())
        
        index = self.comboBox_listdb.findText(a, Qt.MatchFixedString)
        if index >= 0:
            self.comboBox_listdb.setCurrentIndex(index)
        con = p.connections()[self.comboBox_listdb.currentText()]
        if platform.system() == "Windows":
            conn=con.uri().replace("dbname=",'').replace("'","").replace("/","\\")
        else:
            conn=con.uri().replace("dbname=",'').replace("'","")
        return conn
        
    
    # def setPathraster(self):
        
        # s = QgsSettings()
        # dbpath = QFileDialog.getOpenFileName(
            # self,
            # "Set file name",
            # '',
            # "image (*.*)"
        # )[0]
        # #filename=dbpath.split("/")[-1]
        # if dbpath:

            # self.comboBox_raster.setEditText(dbpath)
            # s.setValue('',dbpath)
    
    # def setPathDB(self):
        # s = QgsSettings()
        # filename = QFileDialog.getOpenFileName(
            # self,
            # "Set file name",
            # '',
            # " db sqlite (*.sqlite)"
        # )[0]
        # #filename=dbpath.split("/")[-1]
        # if filename:

            # self.comboBox_listdb.setEditText(filename)
            # s.setValue('',filename)
    
    
    
    
    def on_pushButton_convert_pressed(self):
        QMessageBox.warning(self, "Attenzione",
                                     "Assicurati che il nome del db non abbia parentesi o caratteri spaciali o spazi, altrimenti la conversione fallisce",
                                     QMessageBox.Ok)
        #if self.comboBox_listdb.currentText() == 'sqlite':

        if platform.system() == "Windows":
            b=QgsApplication.qgisSettingsDirPath().replace("/","\\")
            cmd = os.path.join(os.sep, b , 'python', 'plugins', 'spatialite_converter', 'spatialite_convert.exe')
            
            
        
        else:
            QMessageBox.warning(self, "Attenzione",
                                 "Funzione abilitata solo per windows",
                                 QMessageBox.Ok)

        #db1 = os.path.join(os.sep, self.HOME, 'pyarchinit_DB_folder', self.lineEdit_DBname.text())

        # text_ = cmd, self.comboB#ox_compare.currentText(), db1 + ' ', db2
        # result = subprocess.check_output([text_], stderr=subprocess.STDOUT)
        
        try:
            os.system("start cmd /k" + cmd + ' --db-path ' + ' ' +self.test() +' '+ '-tv 4' )
            
        except:
            QMessageBox.warning(self, "Attenzione",
                                 "il db è nella versione 4 verrà convertito nella versione 5",
                                 QMessageBox.Ok)
        else:
            os.system("start cmd /k" + cmd + ' --db-path ' + ' ' + self.test() +' '+ '-tv 5' )
            
    def closeEvent(self, event):
        self.closingPlugin.emit()
        event.accept()
