/*
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"
	"os"

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

// TODO: Rebuild using LinearLayouts
type FilePicker struct {
	id        string
	title     string
	style     tcell.Style
	active    bool
	visible   bool
	focusable bool
	tabbable  bool

	x, y         int
	w, h         int
	wantW, wantH int

	path   string
	wrkDir *os.File

	layout *RelativeLayout

	fileList             *List
	btnSelect, btnCancel *Button
}

var _ Widget = (*FilePicker)(nil)

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

func (w *FilePicker) Init(id string, style tcell.Style) {
	w.id = id
	w.style = style

	w.layout = NewRelativeLayout(fmt.Sprintf("%s-layout", id), style)

	w.btnSelect = NewButton(fmt.Sprintf("%s-select", id), style)
	w.btnSelect.SetLabel("Select")
	w.layout.Add(w.btnSelect, nil, RelAncBR)
	w.btnCancel = NewButton(fmt.Sprintf("%s-cancel", id), style)
	w.btnCancel.SetLabel("Cancel")
	w.layout.Add(w.btnCancel, nil, RelAncBL)
	w.tabbable = true
}
func (w *FilePicker) Id() string { return w.id }
func (w *FilePicker) HandleResize(ev *tcell.EventResize) {
	w.w, w.h = ev.Size()
	// ww, wh := w.w-2, w.h-2 // Trim border space
	w.btnSelect.SetPos(Coord{X: w.x + w.w - w.btnSelect.WantW(), Y: w.y + w.h - 1})
	w.btnCancel.SetPos(Coord{X: w.x + 1, Y: w.y + w.h - 1})
}

func (w *FilePicker) HandleKey(ev *tcell.EventKey) bool {
	if !w.active {
		return false
	}
	return false
}
func (w *FilePicker) HandleTime(ev *tcell.EventTime) {}
func (w *FilePicker) Draw(screen tcell.Screen) {
	if !w.visible {
		return
	}
	ds := w.style
	if !w.active {
		ds = ds.Dim(true)
	}
	wh.TitledBorderFilled(w.x, w.y, w.x+w.w, w.y+w.h, w.title, wh.BRD_SIMPLE, ds, screen)
	// TODO: Draw the file picker
	wh.DrawText(w.x+1, w.y+1, "TODO: Draw Filepicker", ds, screen)
	w.GetPos().DrawOffset(w.btnSelect, screen)
	w.GetPos().DrawOffset(w.btnCancel, screen)
}

func (w *FilePicker) Active() bool       { return w.active }
func (w *FilePicker) SetActive(a bool)   { w.active = a }
func (w *FilePicker) Visible() bool      { return w.visible }
func (w *FilePicker) SetVisible(a bool)  { w.visible = a }
func (w *FilePicker) SetX(x int)         { w.x = x }
func (w *FilePicker) SetY(y int)         { w.y = y }
func (w *FilePicker) GetX() int          { return w.x }
func (w *FilePicker) GetY() int          { return w.y }
func (w *FilePicker) GetPos() Coord      { return Coord{X: w.x, Y: w.y} }
func (w *FilePicker) SetPos(c Coord)     { w.x, w.y = c.X, c.Y }
func (w *FilePicker) SetW(x int)         { w.w = x }
func (w *FilePicker) SetH(y int)         { w.h = y }
func (w *FilePicker) GetW() int          { return w.w }
func (w *FilePicker) GetH() int          { return w.y }
func (w *FilePicker) SetSize(c Coord)    { w.w, w.h = c.X, c.Y }
func (w *FilePicker) Focusable() bool    { return w.focusable }
func (w *FilePicker) SetTabbable(b bool) { w.tabbable = b }
func (w *FilePicker) Tabbable() bool     { return w.tabbable }
func (w *FilePicker) WantW() int {
	// borders + the greater of the buttons next to each other or the list width
	return wh.Max((w.btnSelect.WantW()+w.btnCancel.WantW()), w.fileList.WantW()) + 2
}

func (w *FilePicker) WantH() int {
	// borders + list + buttons
	return 2 + w.fileList.WantH() + w.btnSelect.WantH()
}

func (w *FilePicker) MinW() int {
	return 2 + w.fileList.MinW() + w.btnSelect.MinW() + w.btnCancel.MinW()
}

func (w *FilePicker) MinH() int {
	return 2 + w.fileList.MinH() + w.btnSelect.MinH()
}

func (w *FilePicker) SetTitle(ttl string) { w.title = ttl }
func (w *FilePicker) SetPath(path string) error {
	var err error
	var fl *os.File
	if fl, err = os.Open(path); err != nil {
		return err
	}
	if fs, err := fl.Stat(); err != nil {
		return err
	} else if !fs.IsDir() {
		return fmt.Errorf("path must be a directory")
	}
	w.wrkDir = fl
	w.path = path
	return nil
}

func (w *FilePicker) SetOnSelect(sel func() bool) {
	w.btnSelect.SetOnPressed(sel)
}

func (w *FilePicker) SetOnCancel(cnc func() bool) {
	w.btnCancel.SetOnPressed(cnc)
}
