﻿using Adverty5.Checks;
using System;
using System.Runtime.InteropServices;
using UnityEngine;

namespace Adverty5.AdPlacements
{
    [RequireComponent(typeof(MeshRenderer))]
    [RequireComponent(typeof(MeshFilter))]
    public class MeshAdPlacement : AdPlacement
    {
        private Vector3[] placementVertices;
        private GCHandle verticesHandle;
        private GCHandle modelMatrixHandle;
        protected float[] modelMatrixArray;

        private IntPtr vertices;
        private int vertexCount;
        private IntPtr modelMatrix;

        protected override void Awake()
        {
            base.Awake();
            placementVertices = GetPlacementVerticies();
            vertexCount = placementVertices.Length;
            verticesHandle = GCHandle.Alloc(placementVertices, GCHandleType.Pinned);
            vertices = verticesHandle.AddrOfPinnedObject();
            modelMatrixArray = new float[16];
            modelMatrixHandle = GCHandle.Alloc(modelMatrixArray, GCHandleType.Pinned);
            modelMatrix = modelMatrixHandle.AddrOfPinnedObject();
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();
            verticesHandle.Free();
            modelMatrixHandle.Free();
        }

        internal override Material material
        {
            get {
                return GetComponent<Renderer>().material;
            }
        }

        internal override Texture2D texture
        {
            get {
                return material.mainTexture as Texture2D;
            }
        }

        internal override Vector2Int placementSize
        {
            get {
                return new Vector2Int(Mathf.RoundToInt(transform.lossyScale.x * 100),
                                      Mathf.RoundToInt(transform.lossyScale.y * 100));
            }
        }

        protected override void ApplyPlacementTexture()
        {
            GetComponent<MeshRenderer>().material.mainTexture = adPlacementTexture;
        }

        private Vector3[] GetPlacementVerticies()
        {
            return GetComponent<MeshFilter>().mesh.vertices;
        }

        protected void UpdateMatrix()
        {
            AdvertyViewabilityCheck.MatrixToFloatArray(transform.localToWorldMatrix, modelMatrixArray);
        }

        protected override void ViewabilityCheck()
        {
            UpdateMatrix();
            AdvertyViewabilityCheck.ViewabilityCheckMatrices(Id, modelMatrix, vertices, vertexCount);
        }
    }
}
