#if UNITY_EDITOR

using UnityEditor;
using System.Collections.Generic;
using Stove.StoveSDK;
using UnityEngine;
using System;
using System.IO;

public class PerformBuild
{
    static string[] SCENES = FindEnabledEditorScenes();


    private static string GetArg(string name)
    {
        var args = System.Environment.GetCommandLineArgs();
        for (int i = 0; i < args.Length; i++)
        {
            if (args[i] == name && args.Length > i + 1)
            {
                return args[i + 1];
            }
        }
        return null;
    }


    private static void SetSettings(string zone)
    {
        StoveSettings.Zone = zone;

        StoveSettings.FacebookEnabled = true;
        StoveSettings.FacebookAppId = GetArg("-facebookAppId");
        StoveSettings.FacebookClientToken = GetArg("-facebookClientToken");

        StoveSettings.GoogleEnabled = true;
        StoveSettings.GoogleWebClientId = GetArg("-googleWebClientId");
        StoveSettings.GoogleWebClientSecret = GetArg("-googleWebClientSecret");
        StoveSettings.GoogleIosClientId = GetArg("-googleIosClientId");
        StoveSettings.GoogleIosUrlScheme = GetArg("-googleIosUrlScheme");

        StoveSettings.NaverEnabled = true;
        StoveSettings.NaverClientId = GetArg("-naverClientId");
        StoveSettings.NaverClientSecret = GetArg("-naverClientSecret");
        StoveSettings.NaverClientName = GetArg("-naverClientName");
        StoveSettings.NaverUrlScheme = GetArg("-naverUrlScheme");

        StoveSettings.LineEnabled = true;
        StoveSettings.LineChannelId = GetArg("-lineChannelId");

        StoveSettings.SteamEnabled = true;
        
        StoveSettings.IOSBuildType = GetArg("-iOSBuildType");

        StoveSettings.ONEstoreBuildType = GetArg("-ONEstoreBuildType");

        var foregroundNotificatoinEnabledString = GetArg("-foregroundNotificatoinEnabled");
        var foregroundNotificatoinEnabled = false;
        if(foregroundNotificatoinEnabledString == null)
        {
            foregroundNotificatoinEnabled = false;
        }
        else
        {
            if(foregroundNotificatoinEnabledString == "true")
            {
                foregroundNotificatoinEnabled = true;
            }
            else
            {
                foregroundNotificatoinEnabled = false;
            }
        }

        StoveSettings.ForegroundNotificatoinEnabled = foregroundNotificatoinEnabled;

        var headsUpNotificationEnabledString = GetArg("-headsUpNotificationEnabled");
        var headsUpNotificationEnabled = false;
        if(headsUpNotificationEnabledString == null)
        {
            headsUpNotificationEnabled = false;
        }
        else
        {
            if(headsUpNotificationEnabledString == "true")
            {
                headsUpNotificationEnabled = true;
            }
            else
            {
                headsUpNotificationEnabled = false;
            }
        }

        StoveSettings.HeadsUpNotificationEnabled = headsUpNotificationEnabled;
        
        var sanctionTypeString = GetArg("-sanctionType");
        var sanctionType = false;
        if(sanctionTypeString == null)
        {
            sanctionType = false;
        }
        else
        {
            if(sanctionTypeString == "true")
            {
                sanctionType = true;
            }
            else
            {
                sanctionType = false;
            }
        }

        StoveSettings.SanctionType = sanctionType;

        var pushSmallIcon = GetArg("-pushSmallIcon");
        StoveSettings.PushSmallIcon = pushSmallIcon;

        var enableGUID = GetArg("-enableGUID");
        StoveSettings.EnableGUID = Convert.ToBoolean(enableGUID);

        // 2.9.0 StoveSetting vn 추가
        var enableVTCO = GetArg("-enableVTCO");
        StoveSettings.EnableVTCO = Convert.ToBoolean(enableVTCO);

        /** Google Play Games **/
        var GooglePlayGamesProjectId = GetArg("-googlePlayGamesProjectId");
        if (GooglePlayGamesProjectId == null)
        {
            StoveSettings.GooglePlayGamesEnabled = false;
            StoveSettings.GooglePlayGamesProjectId = "";
        }
        else
        {
            StoveSettings.GooglePlayGamesEnabled = true;
            StoveSettings.GooglePlayGamesProjectId = GooglePlayGamesProjectId;
        }

        StoveSettings.ForegroundNotificatoinEnabled = foregroundNotificatoinEnabled;
        StoveSettings.HeadsUpNotificationEnabled = headsUpNotificationEnabled;

        StoveSettings.AndroidMarket = GetArg("-androidMarket");

        StoveSettings.MarketHuaweiEnabled = true;
        StoveSettings.HuaweiAppId = GetArg("-huaweiAppId");

        var buildAppBundle = GetArg("-buildAppBundle");
        StoveSettings.BuildAppBundle = Convert.ToBoolean(buildAppBundle);
        
        var supportPC = GetArg("-supportPC");
        StoveSettings.SupportPC = Convert.ToBoolean(supportPC);
    }

    [MenuItem("Stove/CI/Build Android")]
    static void BuildAndroid()
    {
        var zone = "sandbox";
        SetSettings(zone);
        
        /** Signing **/
        PlayerSettings.Android.keystoreName = "mvp.keystore";
        PlayerSettings.Android.keyaliasName = "mvp";
        PlayerSettings.Android.keystorePass = "innovation!";
        PlayerSettings.Android.keyaliasPass = "innovation!";

	var buildGroup = BuildPipeline.GetBuildTargetGroup(BuildTarget.Android);

	var androidMarket = StoveSettings.AndroidMarket;
	var packageName = "";
	switch(androidMarket) {
		case "Huawei":
			packageName = "com.stove.mvp.huawei";
			//PlayerSettings.SetScriptingDefineSymbols(NamedBuildTarget.Standalone, "MARKET_HUAWEI");
			PlayerSettings.SetScriptingDefineSymbolsForGroup(buildGroup, "MARKET_HUAWEI");
			break;
		case "OneStore":
		    packageName = "com.stove.mvp.onestore";
            //PlayerSettings.SetScriptingDefineSymbols(NamedBuildTarget.Standalone, "MARKET_ONESTORE");
            PlayerSettings.SetScriptingDefineSymbolsForGroup(buildGroup, "MARKET_ONESTORE");
            break;
        case "VTCO":
            packageName = "com.stove.mvp.google";
            //PlayerSettings.SetScriptingDefineSymbols(NamedBuildTarget.Standalone, "MARKET_ONESTORE");
            PlayerSettings.SetScriptingDefineSymbolsForGroup(buildGroup, "MARKET_VTCO");
            break;
		default:
			packageName = "com.stove.mvp.google";
			//PlayerSettings.SetScriptingDefineSymbols(NamedBuildTarget.Standalone, "MARKET_GOOGLE");
			PlayerSettings.SetScriptingDefineSymbolsForGroup(buildGroup, "MARKET_GOOGLE");
			break;
	}

	/** Setting AndroidArchitecture **/
	PlayerSettings.SetScriptingBackend (BuildTargetGroup.Android, ScriptingImplementation.IL2CPP);
	if (StoveSettings.SupportPC)
	{
		PlayerSettings.Android.targetArchitectures = AndroidArchitecture.All;
	}
	else
	{
		PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARM64 | AndroidArchitecture.ARMv7;
	}

	/** Build App Bundle **/
	if (StoveSettings.BuildAppBundle)
	{
		EditorUserBuildSettings.buildAppBundle = true;
		EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
	}
	else
	{
		EditorUserBuildSettings.buildAppBundle = false;
	}
	
    var promotion = Convert.ToBoolean(GetArg("-promotion"));
	if (promotion)
	{
	    packageName = packageName + ".promotion";
	}

    if (StoveSettings.EnableGUID)
    {
	    packageName = packageName + ".guid";
    }



    // VTCO Build .vn 추가
    if (androidMarket == "VTCO")
    {
        packageName = packageName + ".vn";
    }

	PlayerSettings.applicationIdentifier = packageName;

    var version = GetArg("-sdkVersion");
    Debug.Log("version : " + version);
    if (version == null)
    {
        version = "1.0.0";
    }
    PlayerSettings.bundleVersion = version;

    var bundleVersion = GetArg("-bundleVersion");

    if (bundleVersion == null)
    {
        bundleVersion = "1";
    }

    PlayerSettings.Android.bundleVersionCode = Convert.ToInt32(bundleVersion);

    PlayerSettings.Android.minSdkVersion = AndroidSdkVersions.AndroidApiLevel24;

    var targetSdkVersion = GetArg("-targetSdkVersion");
    Debug.Log("targetSdkVersion : " + targetSdkVersion);
    PlayerSettings.Android.targetSdkVersion = (AndroidSdkVersions)Convert.ToInt32(targetSdkVersion);

    var buildTarget = BuildTarget.Android;
    var buildOptions = BuildOptions.None;
        
	string fileName = "[" + GetArg("-buildNumber") + "]Stove_" + version + "_" + androidMarket;
	PlayerSettings.productName = fileName;
	if (StoveSettings.BuildAppBundle)
	{
		fileName = fileName + ".aab";
	}
	else
	{
		fileName = fileName + ".apk";
	}
	
        GenericBuild(SCENES, fileName, buildTarget, buildOptions);
    }

    [MenuItem("Stove/CI/Build iOS")]
    static void BuildiOS()
    {
        var zone = "sandbox";
        SetSettings(zone);

        // var buildGroup = BuildPipeline.GetBuildTargetGroup(BuildTarget.iOS);

        // var foregroundNotificatoinEnabled = StoveSettings.ForegroundNotificatoinEnabled;
        // if (foregroundNotificatoinEnabled)
        // {
        //     //PlayerSettings.SetScriptingDefineSymbols(NamedBuildTarget.Standalone, "FOREGROUND_NOTIFICATION_ENABLED");
        //     PlayerSettings.SetScriptingDefineSymbolsForGroup(buildGroup, "FOREGROUND_NOTIFICATION_ENABLED");
        // }

        if (StoveSettings.EnableGUID)
        {
            if (StoveSettings.EnableVTCO)
            {
                PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.iOS, "com.stove.mvp.ios.guid.vn");
            }
            else
            {
                PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.iOS, "com.stove.mvp.ios.guid");
            }
            // PlayerSettings.applicationIdentifier = "com.stove.mvp.ios.guid";
        }
        else
        {
            if (StoveSettings.EnableVTCO)
            {
                PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.iOS, "com.stove.mvp.ios.vn");
            }
            else
            {
                PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.iOS, "com.stove.mvp.ios");
            }
            // PlayerSettings.applicationIdentifier = "com.stove.mvp.ios";
        }
        var version = GetArg("-sdkVersion");
        if (version == null)
        {
            version = "1.0.0";
        }
        PlayerSettings.bundleVersion = version;

        var bundleVersion = GetArg("-bundleVersion");

        if (bundleVersion == null)
        {
            bundleVersion = "1";
        }

        PlayerSettings.iOS.buildNumber = bundleVersion;

        PlayerSettings.iOS.sdkVersion = iOSSdkVersion.DeviceSDK;
        PlayerSettings.iOS.targetOSVersionString = "13.0";

        var buildTarget = BuildTarget.iOS;
        var buildOptions = BuildOptions.None;
        string fileName = "[" + GetArg("-buildNumber") + "]Stove_" + version;
        PlayerSettings.productName = fileName;
        GenericBuild(SCENES, fileName, buildTarget, buildOptions);
    }

    private static string[] FindEnabledEditorScenes()
    {
        List<string> EditorScenes = new List<string>();
        foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes)
        {
            if (!scene.enabled) continue;
            EditorScenes.Add(scene.path);
        }
        return EditorScenes.ToArray();
    }

    static void GenericBuild(string[] scenes, string target_filename, BuildTarget buildTarget, BuildOptions buildOptions)
    {
        BuildPipeline.BuildPlayer(scenes, target_filename, buildTarget, buildOptions);
    }

    /********************************************** export sdk to unitypackage **********************************************/
    private static List<string> IGNORE_EXTS = new List<string>();
    private static List<string> IGNORE_FILES = new List<string>();
    private static List<string> IGNORE_DIRS = new List<string>();
    private static List<string> EXPORT_FILES = new List<string>();

    private static void SetIgnoresDefault()
    {
	    IGNORE_EXTS.Clear();
	    IGNORE_EXTS.Add(".DS_Store");
	    IGNORE_EXTS.Add(".meta");

	    IGNORE_FILES.Clear();

	    IGNORE_DIRS.Clear();
	    IGNORE_DIRS.Add("Plugins");

//	    IGNORE_DIRS.Add("Naver");
    }

    private static void GetReadyForExport()
    {
        EXPORT_FILES.Clear();
        SetIgnoresDefault();
    }

    [MenuItem("Stove/CI/All Export")]
	    public static void StoveDeployExportEveryModule()
	    {
		    StoveDeployExportSample();
            StoveDeployExportBase();
            StoveDeployExportLog();
            StoveDeployExportAuth();
		    StoveDeployExportAuthProviderApple();
		    StoveDeployExportAuthProviderFacebook();
		    StoveDeployExportAuthProviderGoogle();
		    StoveDeployExportAuthProviderGooglePlayGames();
		    StoveDeployExportAuthProviderNaver();
		    StoveDeployExportAuthProviderLine();
            StoveDeployExportAuthProviderSteam();
		    StoveDeployExportAuthUi();
            StoveDeployExportIap();
            StoveDeployExportIapGoogle();
            StoveDeployExportIapHuawei();
            StoveDeployExportIapOneStore();
		    StoveDeployExportPush();
		    StoveDeployExportView();
	    }

    [MenuItem("Stove/CI/Export/Full SDK with Sample")]
	    public static void StoveDeployExportSample()
	    {
            GetReadyForExport();
		    GetDirectories("Assets/Stove/SDK");
		    GetDirectories("Assets/Stove/Sample");
		    GetDirectories("Assets/Stove/SSTools");
		    GetDirectories("Assets/Stove/Plugins/iOS");
		    GetDirectories("Assets/Stove/Plugins/Android");
		    
		    RunExport("Sample");
	    }

    [MenuItem("Stove/CI/Export/Base")]
        public static void StoveDeployExportBase()
        {
            GetReadyForExport();
            GetDirectories("Assets/Stove/SDK/Base");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/BaseNativeInterface.h");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/BaseNativeInterface.mm");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/StoveSDKNativeCallbackPayload.h");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/StoveSDKNativeCallbackPayload.m");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/StoveSDKNativeInterface.h");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/StoveSDKNativeInterface.mm");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/StoveSDKNativeNotifyPayload.h");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/StoveSDKNativeNotifyPayload.m");
            RunExport("Base");
        }

    [MenuItem("Stove/CI/Export/Log")]
        public static void StoveDeployExportLog()
        {
            GetReadyForExport();
            GetDirectories("Assets/Stove/SDK/Log");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/LogNativeInterface.h");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/LogNativeInterface.mm");
            RunExport("Log");
        }

    [MenuItem("Stove/CI/Export/Auth")]
        public static void StoveDeployExportAuth()
        {
            GetReadyForExport();
            GetDirectories("Assets/Stove/SDK/Auth");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/AuthNativeInterface.h");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/AuthNativeInterface.mm");
            RunExport("Auth");
        }

    [MenuItem("Stove/CI/Export/AuthProvider-Apple")]
	    public static void StoveDeployExportAuthProviderApple()
	    {
            GetReadyForExport();
		    GetDirectories("Assets/Stove/SDK/AuthProvider/Apple");

		    RunExport("AuthApple");
	    }

    [MenuItem("Stove/CI/Export/AuthProvider-Facebook")]
	    public static void StoveDeployExportAuthProviderFacebook()
	    {
            GetReadyForExport();
		    GetDirectories("Assets/Stove/SDK/AuthProvider/Facebook");

		    RunExport("AuthFacebook");
	    }

    [MenuItem("Stove/CI/Export/AuthProvider-Google")]
	    public static void StoveDeployExportAuthProviderGoogle()
	    {
            GetReadyForExport();
		    GetDirectories("Assets/Stove/SDK/AuthProvider/Google");

		    RunExport("AuthGoogle");
	    }
	    
    [MenuItem("Stove/CI/Export/AuthProvider-GooglePlayGames")]
	    public static void StoveDeployExportAuthProviderGooglePlayGames()
	    {
            GetReadyForExport();
		    GetDirectories("Assets/Stove/SDK/AuthProvider/GooglePlayGames");

		    RunExport("AuthGooglePlayGames");
	    }

    [MenuItem("Stove/CI/Export/AuthProvider-Naver")]
	    public static void StoveDeployExportAuthProviderNaver()
	    {
            GetReadyForExport();
		    GetDirectories("Assets/Stove/SDK/AuthProvider/Naver");

		    RunExport("AuthNaver");
	    }

    [MenuItem("Stove/CI/Export/AuthProvider-Line")]
        public static void StoveDeployExportAuthProviderLine()
        {
            GetReadyForExport();
            GetDirectories("Assets/Stove/SDK/AuthProvider/Line");

            RunExport("AuthLine");
        }

    [MenuItem("Stove/CI/Export/AuthProvider-Steam")]
        public static void StoveDeployExportAuthProviderSteam()
        {
            GetReadyForExport();
            GetDirectories("Assets/Stove/SDK/AuthProvider/Steam");

            RunExport("AuthSteam");
        }

    [MenuItem("Stove/CI/Export/AuthUI")]
	    public static void StoveDeployExportAuthUi()
	    {
            GetReadyForExport();
		    GetDirectories("Assets/Stove/SDK/AuthUI");
		    EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/AuthUINativeInterface.h");
		    EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/AuthUINativeInterface.mm");

		    RunExport("AuthUI");
	    }

    [MenuItem("Stove/CI/Export/View")]
	    public static void StoveDeployExportView()
	    {
            GetReadyForExport();
		    GetDirectories("Assets/Stove/SDK/View");
		    EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/ViewNativeInterface.h");
		    EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/ViewNativeInterface.mm");

		    RunExport("View");
	    }

    [MenuItem("Stove/CI/Export/Push")]
	    public static void StoveDeployExportPush()
	    {
            GetReadyForExport();
		    GetDirectories("Assets/Stove/SDK/Push");
		    EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/PushNativeInterface.h");
		    EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/PushNativeInterface.mm");

		    RunExport("Push");
	    }

    [MenuItem("Stove/CI/Export/IAP")]
	    public static void StoveDeployExportIap()
	    {
            GetReadyForExport();
            IGNORE_DIRS.Add("Google");
            IGNORE_DIRS.Add("OneStore");
            IGNORE_DIRS.Add("Huawei");
	    GetDirectories("Assets/Stove/SDK/IAP");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/IAPNativeInterface.h");
            EXPORT_FILES.Add("Assets/Stove/Plugins/iOS/IAPNativeInterface.mm");

		    RunExport("Iap");
	    }

    [MenuItem("Stove/CI/Export/IAP-Google")]
	    public static void StoveDeployExportIapGoogle()
	    {
            GetReadyForExport();
		    GetDirectories("Assets/Stove/SDK/IAP/Google");

		    RunExport("IapGoogle");
	    }

    [MenuItem("Stove/CI/Export/IAP-OneStore")]
        public static void StoveDeployExportIapOneStore()
        {
            GetReadyForExport();
            GetDirectories("Assets/Stove/SDK/IAP/OneStore");

            RunExport("IapOneStore");
        }

    [MenuItem("Stove/CI/Export/IAP-Huawei")]
        public static void StoveDeployExportIapHuawei()
        {
            GetReadyForExport();
            GetDirectories("Assets/Stove/SDK/IAP/Huawei");

            RunExport("IapHuawei");
        }

    private static void RunExport(string fileName)
    {
        if (!string.IsNullOrEmpty(fileName))
        {
            string version = "2.9.0";
            string ext = ".unitypackage";
            AssetDatabase.ExportPackage(EXPORT_FILES.ToArray(), fileName + "-" + version + ext);
        }
    }

    public static void GetDirectories(string currentDir)
    {
	    string[] directories = Directory.GetDirectories(currentDir);
	    foreach (string dir in directories)
	    {
		    string dirName = Path.GetFileName(dir);
		    bool isIgnoreDir = IGNORE_DIRS.Contains(dirName);
		    if (isIgnoreDir)
			    continue;

		    GetDirectories(dir);
	    }

	    GetFiles(currentDir);
    }

    public static void GetFiles(string currentDir)
    {
	    string[] files = Directory.GetFiles(currentDir);
	    string name;
	    string ext;

	    foreach (string file in files)
	    {
		    name = Path.GetFileName(file);
		    ext = Path.GetExtension(file);

		    if (IGNORE_EXTS.Contains(ext))
			    continue;

		    if (IGNORE_FILES.Contains(name))
			    continue;

		    EXPORT_FILES.Add(file);
	    }
    }
    /************************************************************************************************************************/
}

#endif
