﻿using UnityEditor.Android;
using UnityEngine;
using System.IO;
using System;

namespace Adverty5.Editor
{
    public class GradleProjectPostProcessor : IPostGenerateGradleAndroidProject
    {
        private const string BROWSER_VERSION = "1.0.+";
        private const string BROWSER_ARTIFACT_NAME = "androidx.browser:browser";
        private const string PATCH_CONTENT = "implementation '" + BROWSER_ARTIFACT_NAME + ":" + BROWSER_VERSION + "'";
        private const string LINE_TO_ADD_AFTER = "implementation fileTree(dir: 'libs', include: ['*.jar'])";
        private const string ANDROIDX_SETTING = "android.useAndroidX=true";
        public int callbackOrder
        {
            get {
                return 0;
            }
        }

        private void PatchGradleBuildFile(string filePath)
        {
            string[] lines = File.ReadAllLines(filePath);

            int foundBrowserLine = -1;
            int patchLine = -1;
            for (int lineIndex = 0; lineIndex < lines.Length; lineIndex++)
            {
                if (lines[lineIndex].Contains(BROWSER_ARTIFACT_NAME))
                {
                    foundBrowserLine = lineIndex;
                }

                if (lines[lineIndex].Contains(LINE_TO_ADD_AFTER))
                {
                    patchLine = lineIndex;
                }
            }

            if (foundBrowserLine != -1)
            {
                if (lines[foundBrowserLine].Contains(BROWSER_VERSION))
                {
                    return;
                }

                lines[foundBrowserLine] = PATCH_CONTENT;

                Debug.LogFormat("Gradle Build file was successfully patched. updated browser library to {0}:{1}",
                                BROWSER_ARTIFACT_NAME, BROWSER_VERSION);
            }
            else if (patchLine != -1)
            {
                Array.Resize(ref lines, lines.Length + 1);
                Array.Copy(lines, patchLine + 1, lines, patchLine + 2, lines.Length - patchLine - 2);
                lines[patchLine + 1] = PATCH_CONTENT;
                Debug.LogFormat("Gradle Build file was successfully patched. {0}:{1} was added", BROWSER_ARTIFACT_NAME,
                                BROWSER_VERSION);
            }
            else
            {
                Debug.LogError("Failed to locate line to patch");
                return;
            }

            File.WriteAllLines(filePath, lines);
        }

        private void PatchGradleSettingsFile(string filePath)
        {
            string[] lines = File.ReadAllLines(filePath);

            foreach (string line in lines)
            {
                if (line.Contains(ANDROIDX_SETTING))
                {
                    return;
                }
            }

            Array.Resize(ref lines, lines.Length + 1);
            Array.Copy(lines, 0, lines, 1, lines.Length - 1);
            lines[0] = ANDROIDX_SETTING;
            Debug.LogFormat("Gradle Settings file was successfully patched. {0} setting was added", ANDROIDX_SETTING);

            File.WriteAllLines(filePath, lines);
        }

        public void OnPostGenerateGradleAndroidProject(string path)
        {
            string gradleFilePath = Path.Combine(path, "build.gradle");

            if (!File.Exists(gradleFilePath))
            {
                Debug.LogError("Failed to locate build.gradle file for patching");
                return;
            }

            PatchGradleBuildFile(gradleFilePath);

            DirectoryInfo directoryInfo = new DirectoryInfo(path);
            string rootProjectPath = directoryInfo.Parent.FullName;
            string gradleSettingsFilePath = Path.Combine(rootProjectPath, "gradle.properties");
            if (!File.Exists(gradleSettingsFilePath))
            {
                Debug.LogError("Failed to locate gradle.properties file for patching");
                return;
            }

            PatchGradleSettingsFile(gradleSettingsFilePath);
        }
    }
}
