using Assets.Scripts.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class WorkerController : MonoBehaviour
{
    public static Dictionary<uint, List<Structure>> Workers = new Dictionary<uint, List<Structure>>();
    public static List<Structure> TestStructures = new List<Structure>();

    public GameObject WorkersList; // scroll content
    public Dropdown DropdownCompany;
    public Dropdown DropdownLocation;
    public Dropdown DropdownData;
    public GameObject inputField_date;
    //public InputField inputField_location;
    public GameObject TimeStart;
    public GameObject TimeEnd;
    public GameObject StartHour;
    public GameObject StartMin;
    public GameObject StartSec;
    public GameObject EndHour;
    public GameObject EndMin;
    public GameObject EndSec;
    public GameObject StartStopButton;
    public GameObject ErrorDialog;
    public GameObject ButtonPlay;
    public Dropdown DropdownMode;
    public Toggle ToggleLine;
    public Toggle ToggleDisappearance;
    public GameObject DatePicker;
    public Camera camera;
    public Toggle projection;

    InputField inputField_date_text;

    enum Mode { RealTime = 0, History = 1, Stop = 2 };
    Mode active_mode = Mode.Stop;
    int mode = 0;
    //public GameObject Time;

    static Client client = new Client();

    DateTimePicker Date;

    public List<GameObject> maps;
    static List<bool> starting = new List<bool>(); // флаги остановок
    public static Dictionary<uint, bool> end_send = new Dictionary<uint, bool>(); // флаги завершения загрузки
    Dictionary<uint, MarkerMoving> moving = new Dictionary<uint, MarkerMoving>(); // флаги начала движения
    //bool real_time = false;
    //bool history_start = false;
    float interpolationPeriod = 0.1f;
    float time_realtime = 0;
    float time_draw = 0;
    public static List<User> users = new List<User>();
    public static bool users_load = false;
    uint location_id = 1;

    //List<bool> StartStop = new List<bool>();

    // Start is called before the first frame update
    void Start()
    {
        DebugHelper.ActivateConsole();
        //WorkerMarker(4, Color.red);
        //WorkerMarker(356, Color.green);

        inputField_date_text = inputField_date.transform.GetComponent<InputField>();
        //Year = DatePicker.transform.GetChild(0).GetComponent<Dropdown>();
        //Month = DatePicker.transform.GetChild(1).GetComponent<Dropdown>();
        //Day = DatePicker.transform.GetChild(2).GetComponent<Dropdown>();

        Date = DatePicker.GetComponent<DateTimePicker>();

        //foreach (var s in structures.Select(s => s.acc_id).Distinct())
        //    WorkerMarker(s, UnityEngine.Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f));

        //foreach (var s in structures.Select(s => s.ts.Date).Distinct())
        //{
        //    dates.Add(s);
        //    DropdownData.options.Add(new Dropdown.OptionData(s.ToString("dd.MM.yyyy")));
        //}

        //foreach (var s in structures.Select(s => s.location_id).Distinct())
        //{
        //    locations.Add(s);
        DropdownLocation.options.Add(new Dropdown.OptionData("1 Братск"));
        DropdownLocation.options.Add(new Dropdown.OptionData("22 Офис Ижевск"));
        DropdownLocation.options.Add(new Dropdown.OptionData("25"));

        DropdownCompany.options.Add(new Dropdown.OptionData("Тайшет"));
        DropdownCompany.options.Add(new Dropdown.OptionData("Тестовая"));
        DropdownCompany.options.Add(new Dropdown.OptionData("Братское"));
        //}
    }

    int active_location = 0;
    int active_company = 0;
    // Update is called once per frame
    void Update()
    {
        if (DropdownMode.value != mode)
        {
            StopProgress();

            active_mode = Mode.Stop;
            mode = DropdownMode.value;
            switch (DropdownMode.value)
            {
                case 0:
                    //history_start = false;
                    //////inputField_date.gameObject.SetActive(false);
                    DatePicker.SetActive(false);
                    TimeStart.SetActive(false);
                    TimeEnd.SetActive(false);
                    break;
                case 1:
                    //real_time = false;
                    //////inputField_date.gameObject.SetActive(true);
                    DatePicker.SetActive(true);
                    TimeStart.SetActive(true);
                    TimeEnd.SetActive(true);
                    break;
            }
        }

        if(active_company != DropdownCompany.value)
        {
            active_company = DropdownCompany.value;
            foreach(var m in markers)
            {
                Destroy(m.marker.gameObject);
                Destroy(m.marker_line.gameObject);
                Destroy(m.toggle.gameObject);
            }
            markers = new List<Marker>();
            client.SendGetUsers((uint) active_company + 1);
        }

        if (active_location != DropdownLocation.value)
        {
            maps.ElementAt(active_location).SetActive(false);
            maps.ElementAt(DropdownLocation.value).SetActive(true);
            active_location = DropdownLocation.value;
            switch (DropdownLocation.value)
            {
                case 0:
                    //inputField_location.text = "1";
                    location_id = 1;
                    break;
                case 1:
                    //inputField_location.text = "22";
                    location_id = 22;
                    break;
                case 2:
                    //inputField_location.text = "25";
                    location_id = 25;
                    break;
            }
        }

        foreach (var m in markers)
        {
            m.marker.SetActive(m.toggle.isOn);
            if (m.toggle.isOn && Workers.ContainsKey(m.acc_id) && starting.Last() && end_send[m.acc_id])
            {
                //end_send[m.value.acc_id] = false;
                // moving.Add(true);

                //if (markers.Count - 1 == m.i)
                time_draw += Time.deltaTime;
                if (time_draw >= interpolationPeriod)
                {
                    time_draw -= interpolationPeriod;

                    StartingAccPositiong(m);
                }
            }
        }

        time_realtime += Time.deltaTime;
        if (active_mode == Mode.RealTime /*&& !inputField_location.text.Equals("")*/ && time_realtime >= interpolationPeriod)
        {
            time_realtime -= interpolationPeriod;
            //var dateNow = DateTime.UtcNow.AddHours(3);
            //Time.GetComponent<Text>().text = dateNow.ToString();
            starting.Add(true);
            //var location_id = uint.Parse(inputField_location.text);
            foreach (var m in markers)
            {
                if (m.toggle.isOn)
                {
                    client.CoordinatesRequest(0, 0, 1, location_id, m.acc_id);

                    //history_start = true;
                    end_send[m.acc_id] = false;
                }
            }
        }

        if (ToggleLine.isOn)
        {
            foreach (var m in markers)
                m.marker_line.gameObject.SetActive(true);
            ToggleDisappearance.interactable = true;
        }
        else
        {
            foreach (var m in markers)
            {
                m.marker_line.gameObject.SetActive(false);
                m.marker_line.positionCount = 0;
            }
            ToggleDisappearance.interactable = false;
        }

        if (projection.isOn)
        {
            //camera_2d.SetActive(true);
            //camera_2_5D.SetActive(false);
            camera.orthographic = true;
        }
        else
        {
            //camera_2d.SetActive(false);
            //camera_2_5D.SetActive(true);
            camera.orthographic = false;
        }

        if (users_load)
        {
            foreach(var u in users.OrderBy(u => u.id))
            WorkerMarker(u, Color.green);
            users_load = false;
        }
    }

    public static List<Marker> markers = new List<Marker>();

    /// <summary>
    /// Создание маркера для сотрудника
    /// </summary>
    /// <param name="acc_id"></param>
    void WorkerMarker(User user, Color color)
    {
        var toggle = Instantiate(Resources.Load("GameObjects/Toggle", typeof(Toggle))) as Toggle;
        toggle.name = $"{user.id}";
        toggle.transform.GetChild(1).gameObject.GetComponent<Text>().text = $"{user.id} {user.name}";
        toggle.transform.SetParent(WorkersList.transform);
        toggle.isOn = false;

        var marker = Instantiate(Resources.Load("GameObjects/Capsule", typeof(GameObject))) as GameObject;
        marker.name = $"marker_{user.id}";
        marker.transform.GetChild(0).transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = $"{user.id}";

        marker.GetComponent<Renderer>().material.color = color; // UnityEngine.Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);

        var marker_line = Instantiate(Resources.Load("GameObjects/Line", typeof(LineRenderer))) as LineRenderer;
        marker_line.name = $"marker_line_{user.id}";
        marker_line.startColor = color;
        marker_line.endColor = Color.white;
        marker_line.material.color = color;

        markers.Add(new Marker { acc_id = user.id, marker = marker, toggle = toggle, marker_line = marker_line });
    }

    /// <summary>
    /// Смена положения маркера
    /// </summary>
    /// <param name="pause">Задержка</param>
    /// <param name="step">Шаг до нового положения</param>
    /// <param name="start_pos">Начальное положение</param>
    /// <param name="end_pos">Финальное положение</param>
    /// <param name="worker_marker">Маркер сотрудника</param>
    /// <param name="w">Данные из БД</param>
    /// <param name="count">Номер процесса/запуска</param>
    /// <param name="progress">Номер записи из БД</param>
    /// <param name="all">Всего записей из БД</param>
    /// <returns></returns>
    void Position(float step, Vector3 start_pos, Vector3 end_pos, Marker marker, Structure w, int count, string progress)
    {
        if (marker.marker.activeSelf == true && starting[count])
        {
            var x_position = Mathf.Lerp(start_pos.x, end_pos.x, step);
            var y_position = Mathf.Lerp(start_pos.z, end_pos.z, step);
            //Debug.Log($"marker name={worker_marker.name} time={pause} step={step} sec x={x_position} y={y_position} x0={start_pos.x} y0={start_pos.z} x1={end_pos.x} y1={end_pos.z}");
            var new_position = new Vector3(x_position, 0.5f, y_position);
            if (marker.marker.transform.position != new_position)
            {
                marker.marker.transform.position = new Vector3(x_position, 0.5f, y_position);
                marker.marker_line.SetPosition(marker.marker_line.positionCount++, new Vector3(x_position, 0, y_position));
                if(ToggleDisappearance.isOn)marker.marker_line = LineDisappearance(marker.marker_line);
            }
            marker.marker.transform.GetChild(0).transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = $"{w.acc_id} x={end_pos.x} y={end_pos.z}";
            marker.toggle.transform.GetChild(1).gameObject.GetComponent<Text>().text = $"{w.acc_id} {w.ts.ToString("hh:mm:ss")}{progress}";
        }
    }

    //static IEnumerator RequestPostion(long ts, long te, uint loc, uint account_id)
    //{
    //    client.CoordinatesRequest(ts, te, 1, loc);
    //    yield return new WaitForSeconds(5);
    //    foreach (var t in TestStructures)
    //        Debug.Log(t);
    //}


    /// <summary>
    /// Запуск отрисовки
    /// </summary>
    public void ButtonStart()
    {
        if (active_mode == Mode.Stop)
            foreach (var m in markers)
                m.marker_line.positionCount = 0;

        var button_text = StartStopButton.transform.GetChild(0);
        switch (DropdownMode.value)
        {
            case 0:
                //real_time = !real_time;
                if (active_mode == Mode.Stop/*real_time*/)
                {
                    active_mode = Mode.RealTime;
                    button_text.GetComponent<Text>().text = "Остановить";
                }
                else
                {
                    active_mode = Mode.Stop;
                    button_text.GetComponent<Text>().text = "Отобразить";
                }
                break;
            case 1:
                if (int.Parse(StartHour.GetComponent<InputField>().text) == 99) SceneManager.LoadScene("Editor3D");
                else
                {
                    if (active_mode == Mode.Stop/*real_time*/) active_mode = Mode.History;
                    else active_mode = Mode.Stop;
                }//history_start = !history_start;
                if (active_mode == Mode.History/*history_start*/)
                {
                    starting.Add(true);
                    var date = Date.Date;

                    var time_start = date; //new DateTime(dates.ElementAt(DropdownData.value).Ticks);
                    time_start = time_start.AddHours(int.Parse(StartHour.GetComponent<InputField>().text));
                    time_start = time_start.AddMinutes(int.Parse(StartMin.GetComponent<InputField>().text));
                    time_start = time_start.AddSeconds(int.Parse(StartSec.GetComponent<InputField>().text));
                    Debug.Log(time_start);
                    var time_end = date; //new DateTime(dates.ElementAt(DropdownData.value).Ticks);
                    time_end = time_end.AddHours(int.Parse(EndHour.GetComponent<InputField>().text));
                    time_end = time_end.AddMinutes(int.Parse(EndMin.GetComponent<InputField>().text));
                    time_end = time_end.AddSeconds(int.Parse(EndSec.GetComponent<InputField>().text));
                    foreach (var m in markers)
                    {
                        if (m.toggle.isOn)
                        {
                            client.CoordinatesRequest(time_start.Ticks, time_end.Ticks, 1, location_id, m.acc_id);
                            end_send[m.acc_id] = false;
                        }
                    }
                    button_text.GetComponent<Text>().text = "Остановить";
                }
                else
                {
                    StopProgress();
                }
                break;
        }
    }

    public void ErrorDialogClose()
    {
        ErrorDialog.SetActive(false);
    }

    void StopProgress()
    {
        if (starting.Any()) starting[starting.Count - 1] = false;
        StartStopButton.transform.GetChild(0).GetComponent<Text>().text = "Отобразить";        

        foreach (var m in markers)
        {
            end_send[m.acc_id] = false;
            moving.Remove(m.acc_id);            
        }
    }

    /// <summary>
    /// Затухание траектории
    /// </summary>
    /// <param name="lineRenderer">Траектория</param>
    /// <returns></returns>
    LineRenderer LineDisappearance(LineRenderer lineRenderer)
    {
        //LineRenderer lineRenderer = GetComponent<LineRenderer>();
        int newPositionCount = lineRenderer.positionCount - 1;
        Vector3[] newPositions = new Vector3[newPositionCount];

        for (int i = 0; i < newPositionCount; i++)
        {
            newPositions[i] = lineRenderer.GetPosition(i + 1);
        }
        
        lineRenderer.SetPositions(newPositions);
        return lineRenderer;
    }

    /// <summary>
    /// Смена положения по интервалу
    /// Шаги для плавного перемещения
    /// </summary>
    /// <param name="m">Данные о маркере</param>
    void StartingAccPositiong(Marker m)
    {
        int i = 0;
        float step = 0.1f;
        if (moving.ContainsKey(m.acc_id))
        {
            if (moving[m.acc_id].index < Workers[m.acc_id].Count) i = moving[m.acc_id].index;
            {
                if (moving[m.acc_id].step < 1.1f) step = moving[m.acc_id].step;
            }
        }
        else moving[m.acc_id] = new MarkerMoving();

        var worker = Workers[m.acc_id].OrderBy(wr => wr.ts).ToList();
        if (worker.Any())
        {
            var w = worker.ElementAt(i);
            var start_pos = m.marker.transform.position;
            if (i != 0) start_pos = new Vector3(worker.ElementAt(i - 1).coord_x / 100f, 0.5f, worker.ElementAt(i - 1).coord_y / 100f);
            if (active_mode == Mode.History && i == 0) start_pos = new Vector3(w.coord_x / 100f, 0.5f, w.coord_y / 100f);

            var end_pos = new Vector3(w.coord_x / 100f, 0.5f, w.coord_y / 100f);

            var progress = "";
            if (active_mode == Mode.History) progress = $"\n{i + 1} из {Workers[m.acc_id].Count}";
            Position(step, start_pos, end_pos, m, w, starting.Count - 1, progress);
            // StartingAccPositiong(m.value, time_step);

        }

        if (step >= 1) i++;
        step += interpolationPeriod; // 0.1f;
        moving[m.acc_id].index = i;
        moving[m.acc_id].step = step;
    }

    public void OpenEditor()
    {
        SceneManager.LoadScene("Scenes/Editor2D");
    }

    void OnGUI()
    {
        //if (Input.GetKeyDown(KeyCode.BackQuote)) 
            DebugHelper.DrawConsole();
    }
}

