package model

import "fmt"

type Bolid struct {
	Devices []DevBolid
	Zones   []ZoneBolid
}

type DevBolid struct {
	Name  string
	Type  int64
	Addr  int64
	Input []InputBolid
}

type InputBolid struct {
	ZoneId int64
	Name   string
	Addr   int64
}

type ZoneBolid struct {
	ZoneId int64
	Name   string
	Number int64
}

type ZoneInfo struct {
	ZoneNum  int64
	ZoneName string
	Input    []InputInfo
}

type InputInfo struct {
	DevAdd  int64
	Address int64
}

func (z *ZoneInfo) InputString() string {
	var zones string

	i := 0
	for _, inp := range z.Input {
		if i != 0 {
			zones = zones + ", "
		}
		zones = zones + fmt.Sprint(inp.DevAdd) + "." + fmt.Sprint(inp.Address)
		i++
	}

	return zones
}

func (b *Bolid) ZoneInfo() []ZoneInfo {
	var zonesInfo []ZoneInfo

	for _, zon := range b.Zones {
		var zi ZoneInfo
		for _, dev := range b.Devices {
			var i InputInfo
			for _, inp := range dev.Input {
				if zon.ZoneId == inp.ZoneId {
					zi.ZoneNum = zon.Number
					zi.ZoneName = zon.Name
					i.DevAdd = dev.Addr
					i.Address = inp.Addr
					zi.Input = append(zi.Input, i)
				}
			}
		}
		zonesInfo = append(zonesInfo, zi)
	}

	return zonesInfo
}

func (s *Sirius) NewBolid() *Bolid {
	return &Bolid{
		Devices: s.NewDevices(),
		Zones:   s.NewZones(),
	}
}

func (s *Sirius) NewDevices() []DevBolid {
	var devices []DevBolid

	for _, dev := range s.Device.Get() {
		d := DevBolid{
			Name:  dev.Name,
			Type:  dev.Type,
			Addr:  dev.Addr,
			Input: s.GetInput(dev.DevID),
		}
		devices = append(devices, d)
	}

	return devices
}

func (s *Sirius) GetInput(devId int64) []InputBolid {
	var inputs []InputBolid

	for _, inp := range s.Input.Get() {
		if devId == inp.DevID {
			i := InputBolid{
				ZoneId: inp.ZoneID,
				Name:   inp.Name,
				Addr:   inp.AddrU,
			}
			inputs = append(inputs, i)
		}
	}

	return inputs
}

func (s *Sirius) NewZones() []ZoneBolid {
	var zones []ZoneBolid

	for _, zon := range s.Zone.Get() {
		z := ZoneBolid{
			ZoneId: zon.ZoneID,
			Name:   zon.Name,
			Number: zon.Number,
		}
		zones = append(zones, z)
	}

	return zones
}
