﻿// All rights reserved.
// 
// Copyright (c) 2023 Haï~ (@vr_hai https://www.patreon.com/vr_hai)
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// 
// All rights reserved.
// This version of the software is not open source. Please do not redistribute!
// 
// https://docs.hai-vr.dev/docs/products/facetra-shape-creator

using Hai.FaceTraShape.Components;
using Hai.FaceTraShape.Editor;
using nadena.dev.ndmf;

[assembly: ExportsPlugin(typeof(HFTSCPlugin))]
namespace Hai.FaceTraShape.Editor
{
    [RunsOnAllPlatforms]
    public class HFTSCPlugin : Plugin<HFTSCPlugin>
    {
        protected override void Configure()
        {
            InPhase(BuildPhase.Resolving)
                .Run("Make sure HFTSC restored the original mesh", MakeSureOriginalMeshRestored);
            
            InPhase(BuildPhase.Transforming)
                .Run("Generate HFTSC mesh", DoGenerateFaceTra);
        }

        private static void MakeSureOriginalMeshRestored(BuildContext ctx)
        {
            var creators = ctx.AvatarRootTransform.GetComponentsInChildren<HaiFaceTraShapeCreator>(true);
            foreach (var creator in creators)
            {
                creator.faceMesh.sharedMesh = creator.originalMesh;
            }
        }

        private static void DoGenerateFaceTra(BuildContext context)
        {
            var creators = context.AvatarRootTransform.GetComponentsInChildren<HaiFaceTraShapeCreator>(true);
            foreach (var creator in creators)
            {
                // Run the processor in pipeline mode, so that if other processors
                // has modified the mesh, then it uses the latest version of that mesh.
                new HFTSCProcessor().GenerateMeshAndSet(creator, true);
                UnityEngine.Object.DestroyImmediate(creator);
            }
        }
    }
}