#!/usr/bin/env python
# -*- coding: utf-8 -*-

#    Copyright (C) 2008-2010 Ivan Garcia capiscuas@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 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.Warning

import sys, os, platform
from core.dictionary import *
from PyQt4.QtCore import QSettings, QDir, QVariant
import logging
import shutil
log = logging.getLogger("babiloo.gui.DictFileManager")

class DictFileManager(object):

    def __init__(self, parent, splash):
        self._main = parent
        self.defaultDictsFolder = None
        self.splash = splash
        self.settings = QSettings()

    def getRelativeDictionariesDirectory(self):
        relative_dir = os.path.join(self.getMainApp().programFolder, "dicts")
        if os.path.exists(relative_dir):
            return relative_dir

        return None

    def getHomeUserDictionariesDirectory(self):
        home = unicode(QDir.homePath())
        user_home_dictionary = os.path.join(home, ".babiloo","dicts")
        return user_home_dictionary

    def getSettingsDictionaryDirectory(self):
        settingsDictsDirectory = self.settings.value("settings/dictsDefaultDirectory", QVariant())
        if settingsDictsDirectory == QVariant():
            return None
        else:
            return unicode(settingsDictsDirectory.toString())

    def loadDirectory(self, dirname= None):
        #cleaning the menus with dictionaries first

        for dictId, dictItem in self.getMainApp().menuCheckDictionaries.items():
                self.getMainApp().menuDictionaries.removeAction(dictItem)
                self.getMainApp().engine.deleteDictionary(dictId)

        dirs = []
        dirname = self.getSettingsDictionaryDirectory()
        if dirname:
            dirs.append(dirname)
        dirs.append(self.getRelativeDictionariesDirectory())

        self.getMainApp().engine.dictionaries = {}

        for dirname in dirs:
            if os.path.exists(dirname):

                    for f in os.listdir(dirname):
                            fullpath = os.path.join(dirname, f)
                            if os.path.isfile(fullpath):
                                    self.loadDictionary(fullpath)
                            elif os.path.isdir(fullpath):
                                    for file in os.listdir(fullpath):
                                        self.loadDictionary(os.path.join(fullpath, file))

        self.getMainApp().updateActiveDictionary()

    def loadDictionary(self, file):
        self.splash.showMessage(_("Loading %s...") % os.path.basename(file))
        testdict = self.getMainApp().engine.loadDictionary(file)
        if testdict['loaded']:
            self.getMainApp().loadDictionary(testdict['dict'])

    def saveDictionaryFile(self, dict, dirname = None):
        log.debug('DictFileManager::saveDictionaryFile')

        dictsFolder = self.getSettingsDictionaryDirectory()
        if not dictsFolder:
            dictsFolder = self.getRelativeDictionariesDirectory()

        new_folder = os.path.join(dictsFolder, dict.getFileName())
        if not os.path.isdir(new_folder):
            try:
                log.debug('Creating folder %s' % new_folder)
                os.makedirs(new_folder)
            except:
                log.info('Error creating the folder: %s' % new_folder)
                return

        files = dict.getFilePath()
        if not isinstance(files, list):
            files = [files]
        for file in files:
            new_path = os.path.join(new_folder, os.path.basename(file))
            dict.setFilePath(new_path)

            if os.path.exists(file):
                try:
                    shutil.copy(file, new_path)
                except:
                    log.info('Error copying file to: %s' % new_path)

    def removeDictionaryFile(self, dict):
        filepath = dict.getFilePath()
        if isinstance(filepath, list):
            filepath = filepath[0]
        log.debug('Removing the folder %s'% os.path.dirname(filepath))
        shutil.rmtree(os.path.dirname(filepath))
        return True

    def getMainApp(self):
        return self._main
