﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.Video;

public class QuadSizer : MonoBehaviour
{
   
   [MenuItem("NexTech/Tools/Quad Sizer")]
   public static void SizeQuad()
   {
        // get selection 
        GameObject selection = Selection.activeGameObject;

        // abort if there's no mesh
        if(selection.GetComponent<MeshFilter>() == null)
        {
            Debug.LogError("No mesh on " + selection.name);
            return;
        }

        // abort if there's no quad
        if(selection.GetComponent<MeshFilter>().sharedMesh.name != "Quad")
        {
            Debug.LogError("No Quad mesh on " + selection.name);
            return;
        }

        float height = 0f;
        float width = 0f;

        if(selection.GetComponent<VideoPlayer>() != null)
        {
            // get video
            VideoPlayer video = selection.GetComponent<VideoPlayer>();

            //get resolution
            height = video.height;
            width = video.width;
        }
        else
        {
            // get texture
            Texture2D tex = selection.GetComponent<Renderer>().sharedMaterial.mainTexture as Texture2D;

            if(tex != null)
            {
                //get resolution
                height = tex.height;
                width = tex.width;
            }
            else
            {
                // default to 16:9
                height = 1080f;
                width = 1920f;
            }

            
        }

        //figure out new width
        float tHeight = selection.transform.localScale.y;
        float tWidth = tHeight * width / height;

        //resize
        selection.transform.localScale = new Vector3(tWidth, tHeight, 1f);

        //save changes to disk 
        EditorUtility.SetDirty(selection);


   }

}
