using MiniJSON;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Item : MonoBehaviour
{
    public int PlayerID;
    public int ItemID;

    public GameObject ItemRoot;

    public string Type = "";

    public bool DeleteOnDisconnect = true;

    public string Key
    {
        get { return PlayerID + "_" + ItemID; }
    }

    private NetHost netHost;

    // Start is called before the first frame update
    void Awake()
    {
        netHost = FindObjectOfType<NetHost>();
    }

    private Vector3 lastPos;
    void Start()
    {
        UpdateLastAutoProps();
        
    }

    private void UpdateLastAutoProps()
    {
        lastPos = RootTransform.position;
    }

    public bool IsLocal
    {
        get { return netHost == null || PlayerID == netHost.LocalPlayerID; }
    }

    // Update is called once per frame
    void Update()
    {
        CheckAutoProps();                
    }

    private void CheckAutoProps()
    {
        if (netHost != null && lastPos != RootTransform.position)
        {
            netHost.SendItemUpdate(this);
        }
        UpdateLastAutoProps();
    }

    public Transform RootTransform
    {
        get
        {
            return ItemRoot == null ? transform.root : ItemRoot.transform;
        }
    }

    public void UpdateFromData(Dictionary<string, object> itemData)
    {
        if (itemData.ContainsKey("x") && itemData.ContainsKey("y") && itemData.ContainsKey("z"))
        {
            RootTransform.position = new Vector3(
                                itemData.Key("x", Convert.ToSingle),
                                itemData.Key("y", Convert.ToSingle),
                                itemData.Key("z", Convert.ToSingle)
                            );
        }
    }

    public Dictionary<string, object> GetItemData()
    {
        return new Dictionary<string, object>
        {
            { "x", RootTransform.position.x },
            { "y", RootTransform.position.y },
            { "z", RootTransform.position.z },
            { "item_id", ItemID },
            { "type", Type },
            { "dod", DeleteOnDisconnect },
        };
    }
}
