/*
Copyright © Brian Buller <brian@bullercodeworks.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package widgets

import (
	"fmt"
	"strings"

	wh "git.bullercodeworks.com/brian/tcell-widgets/helpers"
	"github.com/gdamore/tcell"
)

type Table struct {
	id        string
	title     string
	style     tcell.Style
	active    bool
	visible   bool
	focusable bool
	tabbable  bool

	header []string
	footer []string
	data   [][]string

	minimized        bool
	cursorX, cursorY int
	wrapColumns      bool

	border []rune

	x, y int
	w, h int

	columnWidths []int
}

var _ Widget = (*Table)(nil)

type TableSelectMode int

const (
	TableSelectCell = iota
	TableSelectRow
	TableSelectColumn
)

type TableSortDirection int

const (
	TableSortAsc = iota
	TableSortDesc
)

func NewTable(id string, style tcell.Style) *Table {
	ret := &Table{style: style}
	ret.Init(id, style)
	return ret
}

func (w *Table) Init(id string, style tcell.Style) {
	w.id = id
	w.style = style
	w.visible = true
	w.border = wh.BRD_CSIMPLE
	w.tabbable = true
}
func (w *Table) Id() string { return w.id }
func (w *Table) HandleResize(ev *tcell.EventResize) {
	w.w, w.h = ev.Size()

	// w.w = wh.Min(w.w, w.WantW())
	// w.h = wh.Min(w.h, w.WantH())
}

func (w *Table) HandleKey(ev *tcell.EventKey) bool {
	if !w.active {
		return false
	}
	return false
}
func (w *Table) HandleTime(ev *tcell.EventTime) {}
func (w *Table) Draw(screen tcell.Screen) {
	if !w.visible {
		return
	}
	dStyle := w.style
	if w.active {
		dStyle = w.style.Bold(true)
	}
	var dat [][]string
	for i := range w.data {
		dat = append(dat, w.data[i])
	}
	x, y := w.x, w.y
	width, height := w.w, w.h
	if width <= 0 || height <= 0 {
		return
	}
	if !w.active {
		dStyle = dStyle.Dim(true)
	}
	if w.minimized {
		wh.DrawText(x, y, fmt.Sprintf("├%s (%d rows)┤", w.title, len(dat)), dStyle, screen)
		return
	}
	if w.title != "" {
		wh.TitledBorder(x, y, w.x+width, w.y+height, w.title, wh.BRD_CSIMPLE, dStyle, screen)
	} else {
		wh.Border(x, y, w.x+width, w.y+height, wh.BRD_CSIMPLE, dStyle, screen)
	}
	if len(w.header) > 0 {
		wh.DrawText(x, y, fmt.Sprintf("│%s│", strings.Join(w.header, "│")), dStyle, screen)
		y++
	}
	if len(dat) == 0 {
		wh.DrawText(x, y, "No data in table", dStyle, screen)
		y++
	} else {
		for i := range dat {
			wh.DrawText(x, y, fmt.Sprintf("│%s│", strings.Join(dat[i], "│")), dStyle, screen)
			y++
		}
	}
	if len(w.footer) > 0 {
		wh.DrawText(x, y, fmt.Sprintf("│%s│", strings.Join(w.header, "│")), dStyle, screen)
		y++
	}
}

func (w *Table) Active() bool      { return w.active }
func (w *Table) SetActive(a bool)  { w.active = a }
func (w *Table) Visible() bool     { return w.visible }
func (w *Table) SetVisible(a bool) { w.visible = a }
func (w *Table) SetX(x int)        { w.x = x }
func (w *Table) SetY(y int)        { w.y = y }
func (w *Table) GetX() int         { return w.x }
func (w *Table) GetY() int         { return w.y }
func (w *Table) GetPos() Coord     { return Coord{X: w.x, Y: w.y} }
func (w *Table) SetPos(c Coord)    { w.x, w.y = c.X, c.Y }
func (w *Table) SetW(x int)        { w.w = x }
func (w *Table) SetH(y int)        { w.h = y }
func (w *Table) GetW() int         { return w.w }
func (w *Table) GetH() int         { return w.y }

func (w *Table) WantW() int {
	if w.minimized {
		return len(fmt.Sprintf("├%s (%d rows)┤", w.title, len(w.data)))
	}
	// For each column, find the longest (in header, data, and footer)
	var totalW int
	colCnt := wh.Max(len(w.header), len(w.footer))
	for i := range w.data {
		colCnt = wh.Max(colCnt, len(w.data[i]))
	}
	for i := 0; i < colCnt; i++ {
		var cols []int
		if len(w.header) > i {
			cols = append(cols, len(w.header[i]))
		}
		for j := range w.data {
			if len(w.data[j]) > i {
				cols = append(cols, len(w.data[j][i]))
			}
		}
		if len(w.footer) > i {
			cols = append(cols, len(w.footer[i]))
		}
		totalW += wh.Max(cols...)
	}
	return totalW
}

func (w *Table) WantH() int {
	if w.minimized {
		return 1
	}
	datLen := len(w.data) + 2 // Data length + Border
	if len(w.header) > 0 {
		datLen += len(w.header) + 1 // Header length + separator
	}
	if datLen == 0 {
		datLen = 1
	}
	if len(w.footer) > 0 {
		datLen += len(w.footer) + 1 // Footer length + separator
	}
	return datLen
}

func (w *Table) MinW() int {
	if w.minimized {
		return len(fmt.Sprintf("├%s (%d rows)┤", w.title, len(w.data)))
	}
	// For each column, find the longest (in header, data, and footer)
	var totalW int
	colCnt := wh.Max(len(w.header), len(w.footer))
	for i := range w.data {
		colCnt = wh.Max(colCnt, len(w.data[i]))
	}
	for i := 0; i < colCnt; i++ {
		var cols []int
		if len(w.header) > i {
			cols = append(cols, len(w.header[i]))
		}
		for j := range w.data {
			if len(w.data[j]) > i {
				cols = append(cols, len(w.data[j][i]))
			}
		}
		if len(w.footer) > i {
			cols = append(cols, len(w.footer[i]))
		}
		totalW += wh.Max(cols...)
	}
	return totalW
}

func (w *Table) MinH() int {
	if w.minimized {
		return 1
	}
	datLen := wh.Min(len(w.data)+2, 7) // Data length + Border
	if len(w.header) > 0 {
		datLen += len(w.header) + 1 // Header length + separator
	}
	if datLen == 0 {
		datLen = 1
	}
	if len(w.footer) > 0 {
		datLen += len(w.footer) + 1 // Footer length + separator
	}
	return datLen
}

func (w *Table) SetSize(c Coord)    { w.w, w.h = c.X, c.Y }
func (w *Table) Focusable() bool    { return w.focusable }
func (w *Table) SetTabbable(b bool) { w.tabbable = b }
func (w *Table) Tabbable() bool     { return w.tabbable }

func (w *Table) SetTitle(ttl string) { w.title = ttl }
func (w *Table) SetFocusable(f bool) { w.focusable = f }

func (w *Table) SetBorder(b []rune)  { w.border = b }
func (w *Table) AddRow(row []string) { w.data = append(w.data, row) }
func (w *Table) ClearData()          { w.data = [][]string{} }
func (w *Table) GetData() [][]string { return w.data }
