# -*- coding: cp1252 -*-

from PyQt4 import QtCore, QtGui
import os
import os.path

models = None


class AbstractFormView:
    """gère le cycle de vie de sauvegarde d'un formulaire"""
    
    def __init__(self):
        self.saved = True
        self.saveAction.clicked.connect(self.doSave)
    
    def closeEvent(self, event):
        """override Widget::closeEvent()"""
        self.doClose()
        event.accept()
    
    def doUnsave(self):
        self.setWindowTitle("* %s"  % self.file)
        self.saveAction.setEnabled(True)
        self.saved = False
        
    def doSave(self):
        models.SaveData(self.file, self.model)
        self.setWindowTitle("%s"  % self.file)
        self.saveAction.setEnabled(False)
        self.saved = True
        
    def doClose(self):
        if not self.saved:
            reply = QtGui.QMessageBox.question(self, 'Avertissement', 
                     "Sauvergarder?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
            if reply == QtGui.QMessageBox.Yes : self.doSave()
    
    def doSaveFile(self, input, title, filter):
        path = self.absolutePath(str(input.text())) if input.text() else os.path.dirname(str(self.file))
        filename = QtGui.QFileDialog.getSaveFileName(self, title, path, filter)
        if filename: 
            input.setText(self.relativePath(str(filename)))
            
    def doOpenFile(self, input, title, filter):
        path = self.absolutePath(str(input.text())) if input.text() else os.path.dirname(str(self.file))
        filename = QtGui.QFileDialog.getOpenFileName(self, title, path, filter)
        if filename: 
            input.setText(self.relativePath(str(filename)))
            
    def relativePath(self,  path):
        return RelativePath(str(path),  str(self.file))
    
    def absolutePath(self,  relativePath):
        return os.path.join(os.path.dirname(str(self.file)), str(relativePath))

def RelativePath(destination,  rootFile):
    try:
        if os.path.isabs(destination):
            return os.path.relpath(destination, os.path.dirname(rootFile))
        else:
            return destination
    except ValueError:
        return destination
        
if __name__ == "__main__":
    
    print RelativePath("c:\\A\\B\\C\\", "c:\\A\\B\\C\\D\\test.root"),  ".."
    print RelativePath("d:\\A\\B\\C\\", "c:\\A\\B\\C\\D\\test.root"),  "d:\A\B\C\\"
    print RelativePath("c:\\A\\B\E\\", "c:\\A\\B\\C\\D\\test.root"),  "..\..\E\\"
    print RelativePath("c:\\A\\B\\E\\png.file", "c:\\A\\B\\C\\D\\test.root"),  "..\..\E\\png.file"
    print RelativePath("..\\KO\\B\\E\\png.file", "c:\\A\\B\\C\\D\\test.root"),  "..\KO\B\E\\png.file"
    print RelativePath("c:\\A\\B\\C\\D\\test.png", "c:\\A\\B\\C\\D\\test.root"),  "test.png"
    
