using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
using AsImpL;
using System.IO;

[RequireComponent(typeof(ObjectImporter))]
public class ImportingController : MonoBehaviour {


    [SerializeField]
    private DeformationManager deformationManager;

    [SerializeField]
    private ImportOptions options;

    [SerializeField]
    private Transform positionToSpawn;

    [SerializeField]
    private ToggleGroup filesToggleGroup;

    private ObjectImporter objImporter;

    [SerializeField]
    private Button[] importButtons;

    [SerializeField]
    private InputField scaleField;

    [SerializeField]
    private Text _importPathText;

    private List<FileToImport> _files;

    [SerializeField]
    private GameObject _filePrefab;

    [SerializeField]
    private GameObject _fileToggleParent;

    private FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();

    private bool _importAsDeforming = true;

    private string _importPath;

    private void Start()
    {
        _importPath = Path.Combine(Path.GetFullPath(Application.dataPath), "Import");
        _importPathText.text = "Import path: " + _importPath;

        Directory.CreateDirectory(_importPath);

        objImporter = gameObject.GetComponent<ObjectImporter>();

        RefreshFiles();
        objImporter.ImportingStart += DisableImport;

        objImporter.ImportingComplete += EnableImport;

        objImporter.ImportedModel += (model, name) =>
        {
            MeshFilter mesh = model.GetComponentInChildren<MeshFilter>();
            Renderer renderer = model.GetComponentInChildren<Renderer>();
            Texture texture = renderer.material.mainTexture;
            if (!_importAsDeforming)
            {
                deformationManager.SetNonDeformingMesh(mesh);
            } else
            {
                deformationManager.SetNewMesh(Path.GetFileNameWithoutExtension(name), mesh, options.modelScaling, texture);
                deformationManager.HideSkull();
            }
            _importAsDeforming = true;
            Destroy(model);
        };

        scaleField.text = options.modelScaling.ToString(System.Globalization.CultureInfo.InvariantCulture);
    }

    public void ChangeImportScale()
    {
        float newScale = float.Parse(scaleField.text);
        newScale = Mathf.Clamp(newScale, 0, 1000);
        scaleField.text = newScale.ToString(System.Globalization.CultureInfo.InvariantCulture);
        options.modelScaling = newScale;
    }

    public void DisableImport()
    {
        foreach (var button in importButtons)
        {
            button.interactable = false;
        }
    }

    public void EnableImport()
    {
        foreach (var button in importButtons)
        {
            button.interactable = true;
        }
    }

    public void RefreshFiles()
    {
        foreach(var file in _fileToggleParent.GetComponentsInChildren<FileToImport>())
        {
            Destroy(file.gameObject);
        }

        if (!Directory.Exists(_importPath))
        {
            Directory.CreateDirectory(_importPath);
        }
        string[] files = Directory.GetFiles(_importPath, "*obj");
        foreach (string file in files)
        {
            CreateFileToggle(file);
        }
    }

    public void StartImporting(bool importAsDeforming = true)
    {
        _importAsDeforming = importAsDeforming;
        Toggle selectedToggle = filesToggleGroup.ActiveToggles().FirstOrDefault();
        if (selectedToggle != null)
        {
            Debug.Log("starting import");
            FileToImport file = selectedToggle.GetComponent<FileToImport>();
            if (file != null)
            {
                string path = file.Filepath;

                objImporter.ImportModelAsync(file.Filename, path, positionToSpawn, options);
            }
        }
    }

    private void CreateFileToggle(string path)
    {
        GameObject newFile = Instantiate(_filePrefab, _fileToggleParent.transform);
        FileToImport fileToImport = newFile.GetComponent<FileToImport>();

        if (fileToImport != null)
        {
            fileToImport.SetFile(path);
        }

        Toggle toggle = newFile.GetComponent<Toggle>();
        toggle.group = filesToggleGroup;
    }


}
