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 = false;
    public bool SwapOnDisconnect = true;

    public bool ManualDelete = false;

    public Dictionary<string, object> Details = new Dictionary<string, object>();

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

    public void DestroyItem()
    {
        if (netHost != null) netHost.DestroyItem(this);
    }

    private NetHost netHost;
    public NetHost GetNetHost() { return 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 Action OnRemoteUpdated;

    public void UpdateFromData(Dictionary<string, object> itemData)
    {
        Details = 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)
                            );
        }

        if (OnRemoteUpdated != null) OnRemoteUpdated();
    }

    public void SendUpdate()
    {
        if (IsLocal && netHost != null)
        {
            netHost.SendItemUpdate(this);
        }
    }

    public Dictionary<string, object> GetItemData()
    {
        Dictionary<string, object> ret = new Dictionary<string, object>(Details);
        ret["x"] = RootTransform.position.x;
        ret["y"] = RootTransform.position.y;
        ret["z"] = RootTransform.position.z;
        ret["item_id"] = ItemID;
        ret["type"] = Type;
        if (DeleteOnDisconnect)
        {
            ret["delete_on_disconnect"] = true;
        }
        if (SwapOnDisconnect)
        {
            ret["swap_on_disconnect"] = true;
        }
        return ret;
    }
}
