package tui

import (
	"github.com/jroimartin/gocui"
)

func layout(g *gocui.Gui) error {
	maxX, maxY := g.Size()

	if maxX != prevWidth || maxY != prevHeight {
		prevWidth, prevHeight = maxX, maxY
		if chatView, err := g.View("chat"); err == nil {
			updateChatView(chatView)
		}

		//if profileView, err := g.View("profile"); err == nil {
		//	updateProfileView(profileView)
		//}

		if _, err := g.View("users"); err == nil {
			updateContactsView(g)
		}
	}

	if err := layoutSidebar(g, maxY); err != nil {
		updateContactsView(g)
		return err
	}
	if err := layoutChat(g, maxX, maxY); err != nil {
		return err
	}
	if err := layoutInput(g, maxX, maxY); err != nil {
		return err
	}

	return nil
}

func layoutChat(g *gocui.Gui, maxX, maxY int) error {
	if v, err := g.SetView("chat", 21, 0, maxX-1, maxY-5); err != nil {
		if err != gocui.ErrUnknownView {
			return err
		}
		v.Title = " Chat "
		v.Wrap = true
		v.Autoscroll = true
		updateChatView(v)
	}
	return nil
}

func layoutInput(g *gocui.Gui, maxX, maxY int) error {
	if v, err := g.SetView("input", 21, maxY-4, maxX-1, maxY-1); err != nil {
		if err != gocui.ErrUnknownView {
			return err
		}
		v.Title = " Type your message: "
		v.Editable = true
		v.Wrap = true
		if _, err := g.SetCurrentView("input"); err != nil {
			return err
		}
	}
	return nil
}

func layoutSidebar(g *gocui.Gui, maxY int) error {
	if v, err := g.SetView("users", 0, 0, 20, maxY-1); err != nil {
		if err != gocui.ErrUnknownView {
			return err
		}
		v.Title = " Users "
		v.Clear()
		updateContactsView(g)
	}
	return nil
}

func layoutProfile(g *gocui.Gui, maxX, maxY int) error {
	var VIEW_WIDTH int
	if maxX-maxX/6 < 21 {
		VIEW_WIDTH = 50
	} else {
		VIEW_WIDTH = maxX - maxX/3
	}
	if v, err := g.SetView("profile", VIEW_WIDTH, 0, maxX-1, maxY-5); err != nil {
		if err != gocui.ErrUnknownView {
			return err
		}
		v.Title = " Profile "
		v.Wrap = true
		//updateProfileView(v)
	}
	return nil
}
