#include "settingscontroller.h"
#include <QDir>
#include <Common/constants.h>
#include <translatableapp.h>
#include <Manager/settingsmanager.h>

SettingsController::SettingsController(Settings *view)
{
    generalView = view;    
    optionsView = nullptr;
    loadSettings();
}

void SettingsController::saveDefaultDir()
{    
    QString defaultDir = ((Settings *)generalView)->getDefaultDir();    

    QString error("");
    if(SettingsManager::saveDefaultDir(defaultDir))
    {
        ((Settings *)generalView)->setAlwaysAsk(false);
    }
    else
    {
        error = QString(tr("La ruta especificada no corresponde a una ruta de directorio valida"));
    }

    generalView->showSuccess("");
    generalView->showError(error);
}

void SettingsController::saveAlwaysAsk()
{  
    bool isChecked = ((Settings *)generalView)->getAlwaysAsk();
    SettingsManager::saveAlwaysAsk(isChecked);
}

void SettingsController::clearValues()
{
    SettingsManager::clearValues();
    SettingsManager::saveAlwaysAsk(true);
    changeLanguage("es");       
    setLanguage("es");
    ((Settings *)generalView)->setAlwaysAsk(true);
    generalView->showError("");
    generalView->showSuccess(tr("Se han establecido los valores por defecto"));
}

void SettingsController::changeLanguage(QString language)
{
    SettingsManager::saveLanguage(language);

    QCoreApplication *app = QApplication::instance();
    ((TranslatableApp * ) app)->swithLanguage(language);
    generalView->showSuccess("");
    ((Settings *)generalView)->retranslate();
}

void SettingsController::loadSettings()
{   
    QString defaultSaveDir = SettingsManager::getDefaultDir();

    bool alwaysAsk = SettingsManager::getIsAlwaysAsk();

    QString language = SettingsManager::getCurrentLanguage();
    setLanguage(language);

    if(!defaultSaveDir.isNull() && !defaultSaveDir.isEmpty() && QDir(defaultSaveDir).exists())
    {
        ((Settings *)generalView)->setDefaultDir(defaultSaveDir);
        ((Settings *)generalView)->setAlwaysAsk(alwaysAsk);
    }
    else
    {
        ((Settings *)generalView)->setDefaultDir("");
        ((Settings *)generalView)->setAlwaysAsk(true);
    }


}

QString SettingsController::getSettingsLanguage()
{    
    return SettingsManager::getCurrentLanguage();
}

void SettingsController::setLanguage(QString language)
{
    if(language == "es")
    {
        ((Settings *)generalView)->setSpanishLanguage();
    }
    else if(language == "en")
    {
        ((Settings *)generalView)->setEnglishLanguage();
    }
    else
    {
        generalView->showError(tr("No ha sido posible cambiar al idoma seleccionado"));
    }
}


