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

[RequireComponent(typeof(WallSegment))]
public class WallSegmentMeshHandler : MonoBehaviour {

    public Transform meshFilter;

    private WallSegment wallSegment;
    private Mesh wallMesh;
    private Vector2[] uvs;
    private Vector3[] vertices;
    private List<int> verticesToMoveIndexes = new List<int>();

    void Awake() {
        wallSegment = GetComponent<WallSegment>();
        wallMesh = meshFilter.GetComponent<MeshFilter>().mesh;
        vertices = wallMesh.vertices;
        uvs = wallMesh.uv;
        for (int i = 0; i < vertices.Length; i++) {
            if (vertices[i].z > 0) {
                verticesToMoveIndexes.Add(i);
            } else {
                uvs[i].x = 0;
            }
        }
    }

    void LateUpdate() {
        foreach (int vertexToMoveIndex in verticesToMoveIndexes) {
            vertices[vertexToMoveIndex].z = wallSegment.Distance;
            uvs[vertexToMoveIndex].x = vertices[vertexToMoveIndex].z;
        }
        wallMesh.vertices = vertices;
        wallMesh.uv = uvs;
        wallMesh.RecalculateBounds();
    }
}
