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

public static class ObjExporter {

    /// <summary>
    /// Export mesh as OBJ into selected directory with unique name from original file name and timestamp
    /// If contains texture, the .mtl file and the texture in .jpg will be exported as well
    /// </summary>
    /// <param name="exportDirectoryPath">Path to exporting directory</param>
    /// <param name="fileName">Original file name</param>
    /// <param name="meshToExport">Mesh filter containing mesh to export</param>
    /// <param name="exportScale">Scale in which to be exported</param>
    /// <param name="textureToExport">Texture of exported file</param>
    public static void ExportToObj(string exportDirectoryPath, string fileName, MeshFilter meshToExport, float exportScale = 1, Texture2D textureToExport = null)
    {
        fileName += "_deformed_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
        float originalScale = exportScale;
        Debug.Log("starting exporting");
        Directory.CreateDirectory(exportDirectoryPath);

        string filePath = Path.Combine(exportDirectoryPath, fileName + ".obj");

        string materialName = "Material";

        using (StreamWriter newFile = new StreamWriter(filePath))
        {
            // to insert . instead of ,
            var cultureInfo = System.Globalization.CultureInfo.InvariantCulture;

            string line;

            if (textureToExport != null)
            {
                string mtlFileName = SaveTexture(exportDirectoryPath, fileName, materialName, textureToExport);
                line = "mtllib " + mtlFileName;
                newFile.WriteLine(line);
                newFile.WriteLine();
            }
            

            Mesh mesh = meshToExport.mesh;

            // write vertices

            foreach(var vertex in mesh.vertices)
            {
                line = $"v {(-vertex.x * originalScale).ToString(cultureInfo)} {(vertex.y * originalScale).ToString(cultureInfo)} {(vertex.z * originalScale).ToString(cultureInfo)}";
                newFile.WriteLine(line);
            }

            newFile.WriteLine();

            // write normals

            foreach (var normal in mesh.normals)
            {
                line = $"vn {(-normal.x).ToString(cultureInfo)} {(normal.y).ToString(cultureInfo)} {(normal.z).ToString(cultureInfo)}";
                //line = $"vn  0.0 0.0 1.0";
                newFile.WriteLine(line);
            }

            newFile.WriteLine();

            // write texture coords

            foreach (var textCoord in mesh.uv)
            {
                line = $"vt {(textCoord.x).ToString(cultureInfo)} {(textCoord.y).ToString(cultureInfo)}";
                newFile.WriteLine(line);
            }

            newFile.WriteLine();

            if (textureToExport != null)
            {
                newFile.WriteLine("usemtl "+ materialName);
                newFile.WriteLine();
            }

            //newFile.WriteLine("usemtl None");
            //newFile.WriteLine("s 1");
            // write faces
            int[] tris = mesh.triangles;
            for(int i = 0; i < tris.Length; i += 3)
            {
                
                line = $"f {1 + tris[i + 1]}/{1 + tris[i + 1]}/{1 + tris[i + 1]} {1+tris[i]}/{1 + tris[i]}/{1 + tris[i]} {1+tris[i+2]}/{1 + tris[i + 2]}/{1 + tris[i + 2]}";
                newFile.WriteLine(line);
            }
        }

        

        Debug.Log("Succesfully exported");
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="exportDirectoryPath"></param>
    /// <param name="fileName"></param>
    /// <param name="texture"></param>
    /// <returns>Name of mtl file</returns>
    private static string SaveTexture(string exportDirectoryPath, string fileName, string materialName, Texture2D texture)
    {
        
        Directory.CreateDirectory(exportDirectoryPath);

        string texturePath = Path.Combine(exportDirectoryPath, fileName + ".jpg");

        string mtlPath = Path.Combine(exportDirectoryPath, fileName + ".mtl");

        File.WriteAllBytes(texturePath, ImageConversion.EncodeToJPG(texture));

        using (StreamWriter newFile = new StreamWriter(mtlPath))
        {
            newFile.WriteLine("newmtl " + materialName);
            newFile.WriteLine("map_Kd " + Path.GetFileName(texturePath));
        }

        return Path.GetFileName(mtlPath);

    }
}
