using System;
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 static EditorController instance;
    public InputField Name;
    public InputField Image;
    public InputField SizeX;
    public InputField SizeY;
    public GameObject BeaconsContent;
    public GameObject PanelBeaconEdit;
    public GameObject Player;
    public GameObject ButtonMode;
    public GameObject EditorTools;
    public Toggle ToggleScalePanel;
    public Toggle projection;

    public Dropdown DropdownLocation;
    public Transform Locations;
    public Button ButtonAddBeacon;
    public GameObject Dialog;

    public GameObject NewLocation;
    public GameObject plane;

    public Location newLocation;

    public Dictionary<uint, List<Beacon>> Beacons = new Dictionary<uint, List<Beacon>>();

    CompanyController company;
    ModeController mode;
    ToolsController tools;

    public Location EditLocation;

    private void Awake()
    {
        instance = this;
    }

    // Start is called before the first frame update
    void Start()
    {
        company = CompanyController.instance;
        mode = ButtonMode.GetComponent<ModeController>();
        tools = EditorTools.GetComponent<ToolsController>();

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

        var random = new System.Random();
        int number = random.Next(2000000000, Int32.MaxValue);
        uint uintNumber = (uint)(number + (uint)Int32.MaxValue);

        if (NewLocation == null)
        {
            NewLocation = new GameObject();
            NewLocation.transform.SetParent(Locations);
            NewLocation.name = "NewLocation";
            NewLocation.transform.position = Vector3.zero;
            NewLocation.SetActive(false);
            plane = Instantiate(Resources.Load("GameObjects/Plane", typeof(GameObject))) as GameObject;
            plane.transform.SetParent(NewLocation.transform);
            plane.transform.position = new Vector3(plane.transform.localScale.x * 5, 0, plane.transform.localScale.z * 5);
            foreach (var g in Location.contents)
            {
                var go = new GameObject();
                go.name = g;
                go.transform.SetParent(NewLocation.transform);
            }
            newLocation = new Location
            {
                id = uintNumber,
                location = NewLocation,
                walls = new List<Wall>(),
                zones = new List<Zone>(),
                beacons = new List<Beacon>(),
                plane = plane,
                texture_url = ""
            };
            company.locations[newLocation.id] = newLocation;
            company.locations_index.Add(newLocation.id);

            DropdownLocation.options.Add(new Dropdown.OptionData("Новая локация"));

            DropdownLocation.RefreshShownValue();
        }       
    }

   
    // Update is called once per frame
    void Update()
    {        
        if (projection.isOn)
        {
            Camera.main.orthographic = true;
        }
        else
        {
            Camera.main.orthographic = false;
        }
    }

    string texture_url = "";

    /// <summary>
    /// Изменение размеров панели
    /// Загрузка текстуры
    /// </summary>
    public void UpdatePanel()
    {
        var p = company.locations[company.locations_index[company.active_location]].plane;
        if (!Image.text.Equals(texture_url))
        {
            StartCoroutine(SendingFormController.LoadImage(Image.text, p));
            texture_url = Image.text;
        }

        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);
        p.transform.localScale = new Vector3(x, 1, y);
        var scale = p.transform.localScale;
        p.transform.position = new Vector3(scale.x * 5, 0, scale.z * 5);
    }

    public void Save()
    {
        //SceneManager.LoadScene("Location");
        tools.CursorOff();
        if (!Name.text.Equals(""))
        {
            //var location = new Location { id = 0, name = Name.text, beacons = Beacons, zones = WallCreate.Zones, walls = WallCreate.Walls, texture_url = Image.text, plane = plane, location =  NewLocation};
            Location location;
            if (EditLocation.id != 0) location = EditLocation;
            else location = new Location { id = Convert.ToUInt32(4000000000), plane = plane, location = NewLocation };
            location.name = Name.text;
            location.texture_url = Image.text;

            if (WallCreate.Walls.ContainsKey(EditLocation.id)) location.walls.AddRange(WallCreate.Walls[EditLocation.id]);
            //if (WallCreate.Zones.ContainsKey(EditLocation.id)) location.zones.AddRange(WallCreate.Zones[EditLocation.id]);
            if (WallCreate.Zones.ContainsKey(EditLocation.id)) location.zones = WallCreate.Zones[EditLocation.id];
            if (Beacons.ContainsKey(EditLocation.id))
            {
                foreach(var b in Beacons[EditLocation.id])
                {
                    var go = b.beacon;
                    b.x = go.transform.position.x;
                    b.y = go.transform.position.z;
                    b.z = go.transform.position.y;
                }
                location.beacons.AddRange(Beacons[EditLocation.id]);
            }

            company.DropdownLocation.options.Last().text = location.name;

            location.location.name = location.name;
           
            location.Save();
            location.SaveContents();
            mode.Switch();
        }
        else
        {
            Dialog.SetActive(true);
            Dialog.transform.GetChild(0).GetComponent<Text>().text = "Введите название локации";
            Dialog.transform.GetChild(2).GetComponent<Button>().onClick.AddListener(() =>
            {
                Dialog.SetActive(false);
            });
        }
    }

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

    public void AddBeacon(CompanyController company, Beacon b = null)
    {
        //PanelBeaconEdit.SetActive(true);
        var location = company.locations[company.locations_index[company.active_location]];


        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.position = new Vector3(b.x, 0.5f, b.y);
            //beacon.transform.GetChild(0).GetChild(0).GetChild(0).GetComponent<Text>().text 
            beacon.GetComponent<BeaconController>().text_info = $"{b.id}\n{b.vagrant_label}\nuuid={b.uuid}\nmajor={b.major}\nminor={b.minor}\nmac={b.mac}";
            beacon.GetComponent<BeaconController>().id = $"{b.id}";
            if (b.enabled == false) beacon.GetComponent<Renderer>().material.color = Color.grey;
        }
        beacon.transform.SetParent(location.location.transform.GetChild(3).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 { };

        var shader1 = Shader.Find("Outlined/Silhouetted Bumped Diffuse");
        var shader2 = Shader.Find("Standard");
     
        //var text = PanelBeaconEdit.transform.GetChild(0).GetComponent<Text>().text = "";
        //var uuid = PanelBeaconEdit.transform.GetChild(1).GetComponent<InputField>().text = "";
        if (b == null)
        {
            b = new Beacon();
            b.location_id = location.id; 
            b.id = Convert.ToUInt32(4000000000 + Beacons[location.id].Count);
            b.enabled = true;

            BeaconEdit(b, name_beacon);
        }

        button.onClick.AddListener(() =>
             {
                 BeaconEdit(b, name_beacon);
                 b.beacon.GetComponent<Renderer>().material.shader = shader1;
             });
        var button_ok = PanelBeaconEdit.transform.GetChild(7).transform.GetChild(0).GetComponent<Button>();
        button_ok.onClick.RemoveAllListeners();
        button_ok.onClick.AddListener(() =>
        {           
            b.uuid = PanelBeaconEdit.transform.GetChild(2).GetComponent<InputField>().text;
            b.minor = ushort.Parse(PanelBeaconEdit.transform.GetChild(3).GetComponent<InputField>().text);
            b.major = ushort.Parse(PanelBeaconEdit.transform.GetChild(4).GetComponent<InputField>().text);
            b.mac = PanelBeaconEdit.transform.GetChild(5).GetComponent<InputField>().text;
            b.enabled = PanelBeaconEdit.transform.GetChild(6).GetComponent<Toggle>().isOn; 

            PanelBeaconEdit.SetActive(false);
            b.beacon.GetComponent<Renderer>().material.shader = shader2;
        });
        var button_close = PanelBeaconEdit.transform.GetChild(7).transform.GetChild(1).GetComponent<Button>();
        button_close.onClick.AddListener(() =>
        {
            PanelBeaconEdit.SetActive(false);
            b.beacon.GetComponent<Renderer>().material.shader = shader2;
        });

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

        //b.id = (uint)Beacons.Count;
        b.beacon = beacon;
        b.panel_button = panel_button;
       
        Beacons[location.id].Add(b);       
    }

    void BeaconEdit(Beacon b, string name_beacon)
    {
        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.vagrant_label.ToString();
            PanelBeaconEdit.transform.GetChild(3).GetComponent<InputField>().text = $"{b.major}";
            PanelBeaconEdit.transform.GetChild(4).GetComponent<InputField>().text = $"{b.major}";
            PanelBeaconEdit.transform.GetChild(5).GetComponent<InputField>().text = b.mac;
            PanelBeaconEdit.transform.GetChild(6).GetComponent<Toggle>().isOn = b.enabled;
        }
    }
}
