class VectorLayerSaveConflictController:
    def __init__(self, csvVectorLayer, csvDataSourceHandler):        
        self.csvVectorLayer = weakref.ref(csvVectorLayer)
        self.csvDataSourceHandler = csvDataSourceHandler
        self.conflictDialog = None
    
    def handleConflict(self):        
        self._initConflictDialog()
        self.features = self.csvVectorLayer().qgsVectorLayer.getFeatures()
        self.conflictDialog.show()
        self.conflictDialog.exec_()
    
    def _initConflictDialog(self):
        self.conflictDialog = GeoCsvDialogConflict() 
        self.conflictDialog.cancelButton.clicked.connect(self._onConflictCancelButton)
        self.conflictDialog.retryButton.clicked.connect(self._onConflictRetryButton)
        self.conflictDialog.saveAsButton.clicked.connect(self._onConflictSaveAsButton)   
        
    def _onConflictCancelButton(self):
        self.conflictDialog.accept()
    
    def _onConflictRetryButton(self):
        self.conflictDialog.accept()
        try:
            self.csvDataSourceHandler.syncFeaturesWithCsv(self.csvVectorLayer().vectorLayerDescriptor, self.features)
        except FileIOException:
            self.handleConflict()
    
    def _onConflictSaveAsButton(self):        
        filePath = QFileDialog.getSaveFileName(self.conflictDialog, QApplication.translate('VectorLayerSaveConflictController', 'Save File'), "", QApplication.translate('VectorLayerSaveConflictController', 'Files (*.csv *.tsv *.*)'));
        if filePath:
            self.conflictDialog.accept()
            try:
                self.csvDataSourceHandler.moveDataSourcesToPath(filePath)
                self.csvDataSourceHandler.syncFeaturesWithCsv(self.csvVectorLayer().vectorLayerDescriptor, self.features, filePath)
                self.csvVectorLayer().updateGeoCsvPath(filePath)
                NotificationHandler.pushSuccess(QApplication.translate('VectorLayerSaveConflictController', 'CSV File updated'), QApplication.translate('VectorLayerSaveConflictController', 'Changes to layer "{}" successfully stored in csv file.').format(self.csvVectorLayer().qgsVectorLayer.name()))
            except:                
                QMessageBox.information(None, QApplication.translate('VectorLayerSaveConflictController', 'Invalid path'), QApplication.translate('VectorLayerSaveConflictController', 'An error occured while trying to save file on new location. Please try again.'))            
 def _initConflictDialog(self):
     self.conflictDialog = GeoCsvDialogConflict() 
     self.conflictDialog.cancelButton.clicked.connect(self._onConflictCancelButton)
     self.conflictDialog.retryButton.clicked.connect(self._onConflictRetryButton)
     self.conflictDialog.saveAsButton.clicked.connect(self._onConflictSaveAsButton)