using UnityEngine;
using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using System.Collections.Generic;
using System.Xml;

public static class PostProcessor{

    private static Dictionary<string, Dictionary<string, string>> appTextMap = new Dictionary<string, Dictionary<string, string>>() {
        { "ja", new Dictionary<string,string>(){ { "appName", "ポップコーン"}, {"tDescription","許可をすると広告最適化に用いられます。"}, } },
        { "en", new Dictionary<string,string>(){ { "appName", "Popcorn"}, {"tDescription","This identifier will be used to deliver personalized ads to you."}, } },
    };

    private static readonly string BUNDLE_URL_NAME = "jp.usaya.popcorn";
    private static readonly string URL_SCHEME = "popcorn";

    [PostProcessBuild]
    public static void OnPostProcessBuild(BuildTarget target, string path){
        if(target == BuildTarget.iOS){
            PostProcessBuild_iOS(path);
        }
    }

    private static void PostProcessBuild_iOS(string path){
        string projectPath = PBXProject.GetPBXProjectPath(path);
        PBXProject pj = new PBXProject ();
        pj.ReadFromString(File.ReadAllText(projectPath));

        var target = pj.GetUnityFrameworkTargetGuid();
        pj.SetBuildProperty (target, "ENABLE_BITCODE", "NO");
        // Enable Modules (C and Objective-C)をYESに設定する
        pj.SetBuildProperty(target, "CLANG_ENABLE_MODULES", "YES");

        // 通知処理対応
        pj.AddFrameworkToProject(target, "UserNotifications.framework", true);
        pj.AddBuildProperty (target, "OTHER_LDFLAGS", "-lz");
        pj.AddBuildProperty (target, "OTHER_LDFLAGS", "-lsqlite3");
        pj.AddBuildProperty (target, "OTHER_LDFLAGS", "-ObjC");

        // info.plist
        string plistPath = Path.Combine(path, "Info.plist" );
        //インスタンスを作成
        PlistDocument plist = new PlistDocument() ;
        //plistの読み込み 
        plist.ReadFromFile(plistPath) ;
        plist.root.SetBoolean("FirebaseAppDelegateProxyEnabled", false);
        // StatusBarをデフォルトで非表示
        plist.root.SetBoolean("UIStatusBarHidden", false);

        PlistElementArray urlTypesArray = plist.root.CreateArray("CFBundleURLTypes");
        PlistElementDict dict = urlTypesArray.AddDict();
        dict.SetString ("CFBundleURLName",BUNDLE_URL_NAME);
        PlistElementArray schemesArray = dict.CreateArray("CFBundleURLSchemes");
        // URLスキームを追加
        schemesArray.AddString(URL_SCHEME);

        PlistElementArray QueriesSchemesArray = plist.root.CreateArray("LSApplicationQueriesSchemes");
        QueriesSchemesArray.AddString("twitter");
        QueriesSchemesArray.AddString("fb");

        // 内部ライブラリの許可
        plist.root.SetString("NSBluetoothPeripheralUsageDescription","Advertisement would like to use bluetooth.");
        plist.root.SetString("NSCalendarsUsageDescription","Advertisement would like to create a calendar");
        plist.root.SetString("NSCameraUsageDescription","Advertisement would like to use camera.");
        plist.root.SetString("NSLocationWhenInUseUsageDescription","Advertisement would like to use location info.");

        // ATT
        PlistElementArray skAdArray = plist.root.CreateArray("SKAdNetworkItems");
        PlistElementDict dictAd1 = skAdArray.AddDict();
        dictAd1.SetString ("SKAdNetworkIdentifier","238da6jt44.skadnetwork");
        PlistElementDict dictAd2 = skAdArray.AddDict();
        dictAd2.SetString ("SKAdNetworkIdentifier","22mmun2rn5.skadnetwork");
        plist.root.SetString("NSUserTrackingUsageDescription","his identifier will be used to deliver personalized ads to you.");
        
        pj.AddFrameworkToProject(target, "AppTrackingTransparency.framework", false);


        // remove exit on suspend if it exists.
        string exitsOnSuspendKey = "UIApplicationExitsOnSuspend";
        if(plist.root.values.ContainsKey(exitsOnSuspendKey))
        {
            plist.root.values.Remove(exitsOnSuspendKey);
        }

        plist.WriteToFile(plistPath);

        //-- TENJIN --//
        pj.AddFrameworkToProject(target, "AdSupport.framework", false);
        pj.AddFrameworkToProject(target, "iAd.framework", false);

        foreach (KeyValuePair<string, Dictionary<string, string>> entry in appTextMap) {
        
            string appNameConverted = "";
            string tDescriptionConverted = "";
            
            foreach (KeyValuePair<string, string> entryText in entry.Value) {            
        
                switch (entryText.Key){
                    case "appName":
                        appNameConverted = encodeText(entryText.Value);
                        break;
                    case "tDescription":
                        tDescriptionConverted = encodeText(entryText.Value);
                        break;
                    default:
                        break;
                } 
            }
        
            // 格納用ディレクトリ作成
            var lprojDir = string.Format("{0}.lproj", entry.Key);
            if (!Directory.Exists(Path.Combine(path, lprojDir))) {
                Directory.CreateDirectory(Path.Combine(path, lprojDir));
            }
            // InfoPlist.strings 作成
            var lprojFile = string.Format("{0}.lproj/InfoPlist.strings", entry.Key);
            StreamWriter w = new StreamWriter(Path.Combine(path, lprojFile), false);
            w.WriteLine(string.Format("CFBundleDisplayName = \"{0}\";", appNameConverted));
            w.WriteLine(string.Format("NSUserTrackingUsageDescription = \"{0}\";", tDescriptionConverted));
            w.Close();
        
            string fileGuid = pj.AddFile( Path.Combine(path, lprojDir), "/"+lprojDir, PBXSourceTree.Source  );
            pj.AddFileToBuild( target, fileGuid );
            pj.WriteToFile( projectPath );
        }

        File.WriteAllText(projectPath, pj.WriteToString());

    }
    private static string encodeText(string text){
        // 文字コードを変換しておく
        string ret = System.Text.Encoding.UTF8.GetString(
                System.Text.Encoding.Convert(
                    System.Text.Encoding.Unicode,
                    System.Text.Encoding.UTF8,
                    System.Text.Encoding.Unicode.GetBytes(text)
                )
            );  
        return ret;
    }
}
