/****************************************************************************
**
** Copyright (C) 2024 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the release tools of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

// constructor
function Component()
{
    component.loaded.connect(this, Component.prototype.loaded);
    installer.installationFinished.connect(this, Component.prototype.installationFinishedPageIsShown);
    installer.finishButtonClicked.connect(this, Component.prototype.installationFinished);
    installer.valueChanged.connect(this, Component.prototype.reactOnTargetDirChange);

    if (installer.value("os") == "win") {
        var vcredist_msvc_32 = "qt.tools.vcredist_msvc2019_x86";
        var vcredist_msvc_64 = "qt.tools.vcredist_msvc2019_x64";
        var vcredist_32 = "qt.tools.vcredist";
        var vcredist_64 = "qt.tools.vcredist_64";
        if (installer.componentByName(vcredist_msvc_64) &&
           installer.componentByName(vcredist_msvc_32) &&
           installer.componentByName(vcredist_64) &&
           installer.componentByName(vcredist_32)) {
        // Creator needs vcredist 32bit on windows
            component.addDependency(vcredist_msvc_32);
        // for OpenSSL
            component.addDependency(vcredist_32);
        if (systemInfo.currentCpuArchitecture == "x86_64") {
                component.addDependency(vcredist_msvc_64);
            // for OpenSSL
                component.addDependency(vcredist_64);
        }
    }
    }
    if (installer.value("os") == "x11") {
        // set installation directory
        installer.setValue("EmbeddedInstallationRootDir", "/usr/local/Trolltech");
        installer.setValue("EmbeddedToolchainDir", "/usr/local/angstrom/arm");
    }

    // Update the location of the Qt Creator executable and "local" install settings
    Component.prototype.reactOnTargetDirChange("TargetDir", installer.value("TargetDir"));

    // add dependency to licenseservice only if component is available
    var license_service_component = "tools.licenseservice";
    if (isEditionCommercial() && installer.componentByName(license_service_component))
        component.addDependency(license_service_component);
}

Component.prototype.loaded = function()
{
    try {
        if (installer.value("os") == "win" && installer.isInstaller() && !installer.isCommandLineInstance())
            installer.addWizardPageItem(component, "AssociateCommonFiletypesForm", QInstaller.TargetDirectory);
    } catch(e) {
        print(e);
    }
    // set required enterprise specific dependencies.
    if (isEditionCommercial()) {
        var enterpriseDependencies = component.value("Dependencies");
        var enterpriseDependenciesStr = "qt.tools.qtcreator_gui.enterprise.plugins";
        if (enterpriseDependencies) {
            component.setValue("Dependencies", enterpriseDependencies + "," + enterpriseDependenciesStr)
        }
        else {
            component.setValue("Dependencies", enterpriseDependenciesStr)
        }
    }
    else {
        if (installer.isOfflineOnly()) {
            var gplv3LicenseDependency = component.value("Dependencies");
            var gplv3LicenseDependencyStr = "qt.license.gplv3except";
            if (gplv3LicenseDependency) {
                component.setValue("Dependencies", gplv3LicenseDependency + "," + gplv3LicenseDependencyStr)
            }
            else {
                component.setValue("Dependencies", gplv3LicenseDependencyStr)
            }
        }
    }
}

Component.prototype.beginInstallation = function()
{
    if (installer.value("os") === "win")
        component.addStopProcessForUpdateRequest(component.qtCreatorBinaryPath);
}

Component.prototype.reactOnTargetDirChange = function(key, value)
{
    if (key == "TargetDir") {
        component.qtCreatorBinaryPath = value;
        if (installer.value("os") == "win") {
            component.qtCreatorBinaryPath = value + "\\/\\bin\\qtcreator.exe";
            component.qtCreatorBinaryPath = component.qtCreatorBinaryPath.replace(/\//g, "\\");
        } else if (installer.value("os") == "mac") {
            component.qtCreatorBinaryPath = value + "///Qt Creator.app";
            // fix duplicate forward slashes in path
            component.qtCreatorBinaryPath = component.qtCreatorBinaryPath.replace(/\/+/g, "/");
        } else {
            component.qtCreatorBinaryPath = value + "///bin/qtcreator";
            // fix duplicate forward slashes in path
            component.qtCreatorBinaryPath = component.qtCreatorBinaryPath.replace(/\/+/g, "/");
        }
    }
}

registerCommonWindowsFileTypeExtensions = function()
{
    var headerExtensions = new Array("h", "hh", "hxx", "h++", "hpp");

    for (var i = 0; i < headerExtensions.length; ++i) {
        component.addOperation("RegisterFileType",
                               headerExtensions[i],
                               component.qtCreatorBinaryPath + " -client \"%1\"",
                               "C++ Header file",
                               "text/plain",
                               component.qtCreatorBinaryPath + ",3",
                               "ProgId=QtProject.QtCreator." + headerExtensions[i]);
    }

    var cppExtensions = new Array("cc", "cxx", "c++", "cp", "cpp");

    for (var i = 0; i < cppExtensions.length; ++i) {
        component.addOperation("RegisterFileType",
                               cppExtensions[i],
                               component.qtCreatorBinaryPath + " -client \"%1\"",
                               "C++ Source file",
                               "text/plain",
                               component.qtCreatorBinaryPath + ",2",
                               "ProgId=QtProject.QtCreator." + cppExtensions[i]);
    }

    component.addOperation("RegisterFileType",
                           "c",
                           component.qtCreatorBinaryPath + " -client \"%1\"",
                           "C Source file",
                           "text/plain",
                           component.qtCreatorBinaryPath + ",1",
                           "ProgId=QtProject.QtCreator.c");
}

registerWindowsFileTypeExtensions = function()
{
    component.addOperation("RegisterFileType",
                           "ui",
                           component.qtCreatorBinaryPath + " -client \"%1\"",
                           "Qt UI file",
                           "text/plain",
                           component.qtCreatorBinaryPath + ",4",
                           "ProgId=QtProject.QtCreator.ui");
    component.addOperation("RegisterFileType",
                           "pro",
                           component.qtCreatorBinaryPath + " -client \"%1\"",
                           "Qt Project file",
                           "text/plain",
                           component.qtCreatorBinaryPath + ",5",
                           "ProgId=QtProject.QtCreator.pro");
    component.addOperation("RegisterFileType",
                           "pri",
                           component.qtCreatorBinaryPath + " -client \"%1\"",
                           "Qt Project Include file",
                           "text/plain",
                           component.qtCreatorBinaryPath + ",6",
                           "ProgId=QtProject.QtCreator.pri");
    component.addOperation("RegisterFileType",
                           "qbs",
                           component.qtCreatorBinaryPath + " -client \"%1\"",
                           "Qbs Project file",
                           "text/plain",
                           component.qtCreatorBinaryPath + ",5",
                           "ProgId=QtProject.QtCreator.qbs");
    component.addOperation("RegisterFileType",
                           "qs",
                           component.qtCreatorBinaryPath + " -client \"%1\"",
                           "Qt Script file",
                           "text/plain",
                           component.qtCreatorBinaryPath + ",0",
                           "ProgId=QtProject.QtCreator.qs");
    component.addOperation("RegisterFileType",
                           "qml",
                           component.qtCreatorBinaryPath + " -client \"%1\"",
                           "Qt Quick Markup language file",
                           "text/plain",
                           component.qtCreatorBinaryPath + ",7",
                           "ProgId=QtProject.QtCreator.qml");
}

isEditionCommercial = function()
{
    var isOpenSource = "true";
    // check if OPENSOURCE flag is set to 'false' or not defined
    if (['false', 'no', '0', "", null].indexOf(isOpenSource) >= 0)
        return true
    return false
}

Component.prototype.createOperations = function()
{
    // Call the base createOperations and afterwards set some registry settings
    component.createOperations();

    // set edition string
    var edition = "Community"
    if (isEditionCommercial())
        edition = "Enterprise"

    if (installer.value("os") == "win") {
        component.addOperation("CreateShortcut",
                               component.qtCreatorBinaryPath,
                               "@StartMenuDir@\\Qt Creator 14.0.0 (" + edition + ").lnk",
                               "workingDirectory=@homeDir@");

        registerWindowsFileTypeExtensions();

        if (!installer.isCommandLineInstance()) {
            var userInterface = component.userInterface("AssociateCommonFiletypesForm")
            if (userInterface && userInterface.AssociateCommonFiletypesCheckBox.checked)
                registerCommonWindowsFileTypeExtensions();
        } else { // For command line interface
            var result = QMessageBox["question"]("AssociateCommonFiletypes", "Associate common file types ",
                "(.c/.h, .cc/.hh, .cxx/.hxx, .c++/.h++, .cpp/.hpp) with Qt Creator?"
                , QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes);
            if (result == QMessageBox.Yes)
                registerCommonWindowsFileTypeExtensions();
        }

    }
    if (installer.value("os") == "x11") {
        component.addOperation("InstallIcons", installer.value("TargetDir") + "//share/icons" );
        component.addOperation( "CreateDesktopEntry",
                                "org.qt-project.qtcreator.desktop",
                                "Type=Application\nExec=\"" + component.qtCreatorBinaryPath + "\" %F\nName=Qt Creator\nGenericName=The IDE of choice for Qt development.\nIcon=QtProject-qtcreator\nStartupWMClass=qtcreator\nTerminal=false\nCategories=Development;IDE;Qt;\nMimeType=text/x-c++src;text/x-c++hdr;text/x-xsrc;application/x-designer;application/vnd.qt.qmakeprofile;application/vnd.qt.xml.resource;text/x-qml;text/x-qt.qml;text/x-qt.qbs;");
    }
}

function isRoot()
{
    if (installer.value("os") == "x11" || installer.value("os") == "mac")
    {
        var id = installer.execute("/usr/bin/id", new Array("-u"))[0];
        id = id.replace(/(\r\n|\n|\r)/gm,"");
        if (id === "0")
        {
            return true;
        }
    }
    return false;
}

Component.prototype.installationFinishedPageIsShown = function()
{
    isroot = isRoot();
    try {
        // Installer value "DesignStudioInstallOnly" is set in 'qt.default.install' -repository.
        // Value is set to true when only Design Studio is selected for default install.
        if (component.installed && installer.isInstaller() && installer.status == QInstaller.Success && !isroot && installer.value("DesignStudioInstallOnly", "false") == "false")
            installer.addWizardPageItem( component, "LaunchQtCreatorCheckBoxForm", QInstaller.InstallationFinished );
    } catch(e) {
        print(e);
    }
}

Component.prototype.installationFinished = function()
{
    try {
        if (component.installed && installer.isInstaller() && installer.status == QInstaller.Success && !isroot && installer.value("DesignStudioInstallOnly", "false") == "false") {
            var isLaunchQtCreatorCheckBoxChecked = component.userInterface("LaunchQtCreatorCheckBoxForm").launchQtCreatorCheckBox.checked;
            if (isLaunchQtCreatorCheckBoxChecked) {
                if (installer.value("os") == "mac") {
                    // Start via open so that we run with the native architecture
                    installer.executeDetached("/usr/bin/open", new Array(component.qtCreatorBinaryPath), "@homeDir@");
                } else {
                    installer.executeDetached(component.qtCreatorBinaryPath, new Array(), "@homeDir@");
                }
            }
        }
    } catch(e) {
        print(e);
    }
}
