using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

public class Location
{
    public uint id { get; set; }
    public string name { get; set; }
    public List<Wall> walls { get; set; }
    public List<Beacon> beacons { get; set; }
    public GameObject plane { get; set; }
    public string texture_url { get; set; }
    public List<Zone> zones { get; set; }
    public GameObject location { get; set; }

    public void Save()
    {
        foreach (Wall wall in walls)
        {
            wall.Save();
        }
        foreach (var z in zones)
        {
            z.Save();
        }
        Client.BeaconsSave(beacons);
    }

    public void Load()
    {
        Zone.LoadByLocationId(id);
        Wall.LoadByLocationId(id);
        Client.BeaconsRequest(id);
    }

    public static void ReceiveFromServer(byte[] bytedata)
    {
        PlayerController.locations = new List<Location>();

        int read = 5;
        while (read < bytedata.Length)
        {
            var id = BitConverter.ToUInt32(bytedata, read);
            var x = BitConverter.ToSingle(bytedata, read + 4);
            var y = BitConverter.ToSingle(bytedata, read + 8);
            var scalex = BitConverter.ToSingle(bytedata, read + 12);
            var scalez = BitConverter.ToSingle(bytedata, read + 16);
            var posx = BitConverter.ToSingle(bytedata, read + 20);
            var posz = BitConverter.ToSingle(bytedata, read + 24);
            var lenimg = BitConverter.ToUInt16(bytedata, read + 28);
            var img = Encoding.UTF8.GetString(bytedata, read + 30, lenimg);
            var lenname = BitConverter.ToUInt16(bytedata, read + 30 + lenimg);
            var name = Encoding.UTF8.GetString(bytedata, read + 32 + lenimg, lenname);
            read += (32 + lenimg + lenname);
            Debug.Log($"location received read {read} id {id} x {x} y {y} scalex {scalex} scalez {scalez} posx {posx} posz {posz} lenimg {lenimg} img {img} lenname {lenname} name {name}");

            GameObject plane = UnityEngine.Object.Instantiate(Resources.Load("GameObjects/Plane", typeof(GameObject))) as GameObject;
            plane.transform.position = new Vector3(posx, 0.01f, posz);
            plane.transform.localScale = new Vector3(scalex, WallCreate.WallHeight, scalez);

            PlayerController.locations.Add(new Location { id = id, name = name, texture_url = img, plane = plane });
        }
        PlayerController.load_location = true;
    }
}

