#include "packagewizard.h"

PackageWizard::PackageWizard(const QString &appDir, QString workspaceWizardLocation, QSettings *vagoSettings)
    :AbstractWizard(appDir, workspaceWizardLocation, vagoSettings, false)
{
    this->packagesLocation=this->workspaceWizardLocation+"/Packages";
}

void PackageWizard::exec(){
    PackagePage2 *page2 = new PackagePage2();
    PackagePage3 *page3 = new PackagePage3();
    PackagePage4 *page4 = new PackagePage4();
    this->page4Pointer = page4; // save the pointer in class variable
    PackagePageFinal *pageFinal = new PackagePageFinal(this->vagoSettings);

    myWizard.addPage(
        createIntroPage(
                        "Welcome to the Anniversary Edition Installer 2 (AIE2) package"
                         " creator wizard.\n"
                         "This wizard will allow you to create in a few and simple steps a package for AIE2."
                        )
   );
    myWizard.addPage(page2);
    myWizard.addPage(page3);
    myWizard.addPage(page4);
    myWizard.addPage(pageFinal);

    showWizard("AIE2 Package Creator", ":/new/icons/package.png");
}


void PackageWizard::createPackage(){
    const QString aeVersion="2.0";

    //Get info page 2
    QString modName=this->myWizard.field("leModName").toString();
    QString authors=this->myWizard.field("leAuthors").toString();
    QString version=this->myWizard.field("leVersion").toString();
    QString description=this->myWizard.field("ptDescription").toString();
    QString packageNumber=this->myWizard.field("lePackageNumber").toString();
    bool bslReplace=this->myWizard.field("rbReplace").toBool();

    //Get info page 3
    QString dependentPackages=this->myWizard.field("leDependentPackages").toString();
    QString incompatiblePackages=this->myWizard.field("leIncompatiblePackages").toString();
    QString unlockLevels=this->myWizard.field("leUnlockLevels").toString();

    //Get info page 4
    const DropTableWidget *commonTable=this->page4Pointer->commonTable;
    const DropTableWidget *windowsTable=this->page4Pointer->windowsTable;
    const DropTableWidget *macTable=this->page4Pointer->macTable;

    //Get info from final page
    bool openFolder=this->myWizard.field("cbOpenFolder").toBool();
    bool createZip=this->myWizard.field("cbCreateZip").toBool();
    //Remember the final page choices to next time
    this->vagoSettings->setValue("PackageCreator/OpenFolder",openFolder);
    this->vagoSettings->setValue("PackageCreator/CreateZip",createZip);

    const QString packageName=packageNumber+Util::String::fullTrim(modName);

    // Start package creation...

    // Create Packages folder if it doesn't exist
    if(!QDir(this->packagesLocation).exists()){
        QDir().mkpath(this->packagesLocation);
    }

    QString modDir=this->packagesLocation+"/"+packageName+"/";

    QDir().mkdir(modDir);

    bool bslExist=false;

    if(commonTable->rowCount()>0){
        copyPackageFolders(commonTable,"common",modDir,bslExist);
    }

    if(windowsTable->rowCount()>0){
        copyPackageFolders(windowsTable,"win_only",modDir,bslExist);
    }

    if(macTable->rowCount()>0){
        copyPackageFolders(macTable,"mac_only",modDir,bslExist);
    }

    QFile modInfo(modDir+"Mod_Info.cfg");

    if (!modInfo.open(QIODevice::WriteOnly | QIODevice::Text)){ //open to write
        UtilVago::showAndLogErrorPopUp("Couldn't create Mod_Info.cfg file when creating AE Package.");
        return;
    }

    QTextStream modWriteStream(&modInfo);
    modWriteStream << "AEInstallVersion -> "+aeVersion+"\n";
    modWriteStream << "NameOfMod -> "+modName+"\n";
    modWriteStream << "ModVersion -> "+version+"\n";
    modWriteStream << "Creator -> "+authors+"\n";
    modWriteStream << "Readme -> "+description.replace("\n"," \\n ")+"\n";
    if(!incompatiblePackages.isEmpty()){
        modWriteStream << "IncompatibleWith -> "+incompatiblePackages+"\n";
    }
    if(!dependentPackages.isEmpty()){
        modWriteStream << "DependsOn -> "+dependentPackages+"\n";
    }

    if(bslExist){
        if(bslReplace){
            modWriteStream << "HasBsl -> Yes\n";
        }
        else{
            modWriteStream << "HasBsl -> Addon\n";
        }
    }

    if(!unlockLevels.isEmpty()){
        modWriteStream << "UnlockLevel -> "+unlockLevels+"\n";
    }

    modWriteStream << "Vago -> "+GlobalVars::AppVersion;

    modInfo.close();

    if(createZip){
        if(!JlCompress::compressDir(this->packagesLocation+"/"+packageName+".zip", modDir)){
            UtilVago::showAndLogErrorPopUp("An error occurred while zipping the package.");
        }
    }

    if(openFolder){
        QDesktopServices::openUrl(QUrl("file:///"+this->packagesLocation));
    }
}

void PackageWizard::copyPackageFolders(const DropTableWidget *myTable, QString tableDir, QString modDir, bool &bslExist){

    QString sourceFolder;
    bool onisExist=false;
    QString path;

    for(int i=0; i<myTable->rowCount(); i++){

        sourceFolder=myTable->item(i,2)->text();

        if(myTable->item(i,1)->text()==".oni"){
            path=modDir+"oni/"+tableDir;
            if(!onisExist){
                onisExist=true;
            }
        }
        else if(myTable->item(i,1)->text()==".bsl"){
            path=modDir+"bsl/"+tableDir;
            if(!bslExist){
                bslExist=true;
            }
        }
        else{
            path=modDir+"patches/"+tableDir;
            if(!bslExist){
                bslExist=true;
            }
        }
        QDir().mkpath(path); //create path if doesn't exist
        if(!Util::FileSystem::copyDir(sourceFolder,path,false)){//copy contents (creates dest destination automatically if not exists yet)

         UtilVago::showAndLogErrorPopUpLogButton("An error occurred while copying the folder/files to the package folder: \n"
                                                        "Copying from "+sourceFolder+"\n to "+path);
        }
    }
}

void PackageWizard::beforeClose(QDialog::DialogCode resultStatus){

    //If wizard finished with sucess, create the package
    if(resultStatus == QDialog::Accepted){
        createPackage();
    }
}

