using System.Collections.Generic;
using System.Linq;
using UnityEngine;

#if UNITY_IOS

namespace Guru.Editor
{
    using UnityEditor;
    using System;
    using System.IO;
    using UnityEditor.Callbacks;
    
    
    public class IOSPostBuild_Firebase_VersionFix
    {

        
        private static string[] fixedLibs = new string[]
        {
            "Firebase/Core",
            "Firebase/Firestore",
            "Firebase/Analytics",
            "Firebase/Storage",
            "Firebase/Auth",
            "Firebase/Messaging",
            "Firebase/Crashlytics",
            "Firebase/DynamicLinks",
            "Firebase/RemoteConfig",
        };
            
        private static string[] additionLibs = new string[]
        {
            "FirebaseFirestoreInternal",
        };
           
        private static string fixedVersion = "10.22.0";
        private static string minTargetSdk = "8.0";    
        
        //  <iosPod name="Firebase/Core" version="10.22.0" minTargetSdk="8.0" />

        
        
        // Firebase 10.20.0 fixed to 10.22.0. BUT higher version do not open this ATTRIBUTE !! 
        // [PostProcessBuild(47)] // MAX POD Process Order
        public static void PostBuildFixPodDeps(BuildTarget target, string projPath)
        {
            if (target != BuildTarget.iOS) return;

            string podfile = Path.Combine(projPath, "Podfile");
            if (!File.Exists(podfile)) return;
            
            FixFirebasePodVersion(podfile);
        }
        
        
        private static void FixFirebasePodVersion(string podfile)
        {
            var lines = File.ReadAllLines(podfile).ToList();
            string line = "";
            int idx = 0;
            bool isDirty = false;
            List<string> needAdded = new List<string>(additionLibs);
            for (int i = 0; i < lines.Count; i++)
            {
                line = lines[i];

                if (line.Contains("pod '"))
                {
                    idx = i;
                }

                foreach (var libName in fixedLibs)
                {
                    if (line.Contains(libName))
                    {
                        lines[i] =  FixOneFirebaseLibVersion(line, fixedVersion);
                        isDirty = true;
                    }
                }

                foreach (var libName in additionLibs)
                {
                    if (line.Contains(libName))
                    {
                        needAdded.Remove(libName);
                        lines[i] =  FixOneFirebaseLibVersion(line, fixedVersion);
                        isDirty = true;
                    }
                }
            }
            
            if (needAdded.Count > 0)
            {
                //  pod 'Firebase/DynamicLinks', '10.20.0'
                foreach (var libName in needAdded)
                {
                    idx++;
                    idx = Mathf.Min(idx, lines.Count - 1);
                    lines.Insert(idx, $"\tpod '{libName}', '{fixedVersion}'");
                    isDirty = true;
                }
            }
            
            if(isDirty) File.WriteAllLines(podfile, lines);
        }

        private static string FixOneFirebaseLibVersion(string line, string fixedVersion)
        {
            if(!line.Contains("', '") || !line.Contains("pod")) return line;
            string fixedLine = line.Substring(0, line.IndexOf("', '") + 4) + $"{fixedVersion}'";
            return fixedLine;
        }
    }
}



#endif