﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace ARGOEditor
{
    public class Builder
    {
        protected readonly Dictionary<BuildTarget, string> Paths = new Dictionary<BuildTarget, string>();
        private const string CommonBuildPath = "Artifacts/AssetBundles/";
        protected const string BundleName = "asset.zip";

        protected Builder()
        {
            FillPaths();
            CreateDirectoriesIfNeeded();
        }

        public void Clean()
        {
            foreach (var obj in Paths)
            {
                CleanDirectory(new DirectoryInfo(obj.Value));
            }
        }

        public void Build(List<BuildTarget> targets, List<GameObject> gameObjects)
        {
            var prefabPath = AssetDatabase.GetAssetPath(gameObjects[0]);

            if (string.IsNullOrEmpty(prefabPath))
            {
                EditorUtility.DisplayDialog("Error occurred", "Can not get prefab path from selected GameObject", "OK");
                return;
            }

            foreach (var t in targets)
            {
                BuildPipeline.BuildAssetBundle(gameObjects[0], gameObjects.ToArray(), Paths[t] + BundleName, out uint crc, BuildAssetBundleOptions.CollectDependencies, t);
            }
        }

        private void FillPaths()
        {
            Paths.Add(BuildTarget.Android, CommonBuildPath + "android/");
            Paths.Add(BuildTarget.iOS, CommonBuildPath + "ios/");
            Paths.Add(BuildTarget.WebGL, CommonBuildPath + "webgl/");
        }

        private void CreateDirectoriesIfNeeded()
        {
            if (!Directory.Exists(CommonBuildPath)) Directory.CreateDirectory(CommonBuildPath);
            foreach (var obj in Paths)
            {
                if (!Directory.Exists(obj.Value))
                {
                    Directory.CreateDirectory(obj.Value);
                }
            }
        }

        private static void CleanDirectory(DirectoryInfo directory)
        {
            foreach (var file in directory.GetFiles()) file.Delete();
            foreach (var subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
        }
    }
}
