using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

/// <summary>
/// Редактор
/// </summary>
public class EditorController : MonoBehaviour
{
    public InputField Name;
    public InputField Image;
    public InputField SizeX;
    public InputField SizeY;
    public GameObject plane;
    public GameObject BeaconsContent;
    public GameObject PanelBeaconEdit;
    public GameObject Player;
    public GameObject ButtonMode;
    public GameObject EditorTools;
    public Toggle ToggleGrid;
    public Toggle ToggleScalePanel;
    public Toggle projection;
    public GameObject Grid;
    public Dropdown DropdownLocation;
    public Transform Locations;
    public Button ButtonAddBeacon;
    public GameObject Dialog;

    public List<Beacon> Beacons = new List<Beacon>();

    PlayerController player;
    ModeController mode;
    ToolsController tools;
    Client client;

    // Start is called before the first frame update
    void Start()
    {
        client = Client.instance;
        player = Player.GetComponent<PlayerController>();
        mode = ButtonMode.GetComponent<ModeController>();
        tools = EditorTools.GetComponent<ToolsController>();

        ButtonAddBeacon.onClick.AddListener(() => {
            AddBeacon();
        });
    }

    // Update is called once per frame
    void Update()
    {
        SizeX.text = $"{plane.transform.localScale.x}";
        SizeY.text = $"{plane.transform.localScale.z}";
        if (ToggleGrid.isOn != Grid.activeSelf) Grid.SetActive(ToggleGrid.isOn);
        if (ToggleScalePanel.isOn != plane.GetComponent<TouchScript>().activeScript) plane.GetComponent<TouchScript>().activeScript = ToggleScalePanel.isOn;

        if (projection.isOn)
        {
            Camera.main.orthographic = true;
        }
        else
        {
            Camera.main.orthographic = false;
        }


        PlayerController.LoadMaps(DropdownLocation, Locations.gameObject);
    }

    public void UpdatePanel()
    {
        if (!Image.text.Equals(""))
            StartCoroutine(SendingFormController.LoadImage(Image.text, plane));

        var x = 1f;
        if (!SizeX.text.Equals(""))
            x = float.Parse(SizeX.text, CultureInfo.InvariantCulture);
        var y = 1f;
        if (!SizeY.text.Equals(""))
            y = float.Parse(SizeY.text, CultureInfo.InvariantCulture);
        plane.transform.localScale = new Vector3(x, 1, y); 
        var scale = plane.transform.localScale;
        plane.transform.position = new Vector3(scale.x * 5, 0, scale.z * 5);
    }

    public void Save()
    {
        //SceneManager.LoadScene("Location");
        tools.CursorOff();      
        if (!Name.text.Equals("")) {
            var l = new Location { id = (uint) PlayerController.locations.Count, name = Name.text };
            PlayerController.locations.Add(l);
            player.DropdownLocation.options.Add(new Dropdown.OptionData(l.name));

            var location = new GameObject();
            location.name = l.name;
            location.transform.SetParent(Locations);
            foreach (var w in WallCreate.Walls)
                w.transform.SetParent(location.transform);


            Client.BeaconsSaveAll();
            mode.Switch();
        }
        else {
            Dialog.SetActive(true);
            Dialog.transform.GetChild(0).GetComponent<Text>().text = "Введите название локации";
        }
    }

    public void Back()
    {
        //SceneManager.LoadScene("Location");
        mode.Switch();
    }

    public void AddBeacon(Beacon b = null)
    {
        //PanelBeaconEdit.SetActive(true);
        
        var beacon = Instantiate(Resources.Load("GameObjects/Beacon", typeof(GameObject))) as GameObject;
        if(ModeController.editor) beacon.GetComponent<BeaconController>().mode = BeaconController.Mode.Editor;
        
        beacon.name = $"Beacon_{b?.id.ToString() ?? Beacons.Count.ToString()}";
        if (b != null)
        {           
            beacon.transform.position = new Vector3(b.x / 100, 0.5f, b.y / 100);
            //beacon.transform.GetChild(0).GetChild(0).GetChild(0).GetComponent<Text>().text 
            beacon.GetComponent<BeaconController>().text_info= $"{b.id}\nuuid={b.uuid}\nmajor={b.major}\nminor={b.minor}";
            beacon.GetComponent<BeaconController>().id = $"{b.id}";
            if(b.enabled == false) beacon.GetComponent<Renderer>().material.color = Color.grey;
        }
        beacon.transform.SetParent(GameObject.Find("Beacons").transform);          
        var name_beacon = $"Маяк {b?.id.ToString() ?? Beacons.Count.ToString()}";
        PanelBeaconEdit.transform.GetChild(0).GetComponent<Text>().text = name_beacon;
        var panel_button = Instantiate(Resources.Load("GameObjects/Panel_Beacon", typeof(GameObject))) as GameObject;
        panel_button.transform.SetParent(BeaconsContent.transform);
        panel_button.name = $"Beacon_{b?.id.ToString() ?? Beacons.Count.ToString()}";
        var button = panel_button.transform.GetChild(0).GetComponent<Button>();      
        button.name = $"BeaconButton_{Beacons.Count}";
        
        button.transform.GetChild(0).GetComponent<Text>().text = name_beacon;

        //var b = new Beacon { };

        button.onClick.AddListener(() =>
        {
            PanelBeaconEdit.SetActive(true);
            PanelBeaconEdit.transform.GetChild(0).GetComponent<Text>().text = name_beacon;
            if (b != null)
            {
                PanelBeaconEdit.transform.GetChild(1).GetComponent<InputField>().text = b.uuid;
                PanelBeaconEdit.transform.GetChild(2).GetComponent<InputField>().text = $"{b.major}";
                PanelBeaconEdit.transform.GetChild(3).GetComponent<InputField>().text = $"{b.major}";
            }
        });
        //var text = PanelBeaconEdit.transform.GetChild(0).GetComponent<Text>().text = "";
        //var uuid = PanelBeaconEdit.transform.GetChild(1).GetComponent<InputField>().text = "";
        if (b == null) b = new Beacon();
        var button_ok = PanelBeaconEdit.transform.GetChild(5).transform.GetChild(0).GetComponent<Button>();
        button_ok.onClick.AddListener(() =>
        {
            b.uuid = PanelBeaconEdit.transform.GetChild(1).GetComponent<InputField>().text;
            b.minor = ushort.Parse(PanelBeaconEdit.transform.GetChild(2).GetComponent<InputField>().text);
            b.major = ushort.Parse(PanelBeaconEdit.transform.GetChild(3).GetComponent<InputField>().text);

            PanelBeaconEdit.SetActive(false);
        });
        var button_close = PanelBeaconEdit.transform.GetChild(5).transform.GetChild(1).GetComponent<Button>();
        button_close.onClick.AddListener(() =>
        {
            PanelBeaconEdit.SetActive(false);
        });

         var button_del = panel_button.transform.GetChild(2).GetComponent<Button>();
        button_del.onClick.AddListener(() =>
        {
            Destroy(beacon);
            Destroy(panel_button);
            Beacons.Remove(b);
            if (PanelBeaconEdit.activeSelf) PanelBeaconEdit.SetActive(false);
        });

        //b.id = (uint)Beacons.Count;
        b.beacon = beacon;
        b.panel_button = panel_button;

        Beacons.Add(b);
    }
}
