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

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

type TimeField struct {
	id       string
	label    string
	style    tcell.Style
	active   bool
	visible  bool
	tabbable bool

	x, y int
	w, h int

	value      time.Time
	hasDate    bool
	hasTime    bool
	hasSeconds bool

	showNowBtn   bool
	nowBtnActive bool

	cursor int
	keyMap KeyMap
}

// TODO: Allow changing the format.
// For now it's just yyyy-mm-dd hh:mm:ss

var _ Widget = (*TimeField)(nil)

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

func (w *TimeField) Init(id string, style tcell.Style) {
	w.id = id
	w.style = style
	w.hasDate = true
	w.hasTime = true
	w.showNowBtn = true
	w.keyMap = NewKeyMap(map[tcell.Key]func(ev *tcell.EventKey) bool{
		tcell.KeyLeft:  w.handleLeft,
		tcell.KeyRight: w.handleRight,
		tcell.KeyHome:  w.handleHome,
		tcell.KeyEnd:   w.handleEnd,
	})
	w.tabbable = true
}

func (w *TimeField) Id() string { return w.id }
func (w *TimeField) 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 *TimeField) HandleKey(ev *tcell.EventKey) bool {
	if !w.active {
		return false
	}
	return false
}
func (w *TimeField) HandleTime(ev *tcell.EventTime) {}
func (w *TimeField) Draw(screen tcell.Screen) {
	if !w.visible {
		return
	}
	ds := w.style
	if !w.active {
		ds = ds.Dim(true)
	}
	x := w.x
	labelW := len(w.label)
	if labelW > 0 {
		wh.DrawText(w.x, w.y, w.label+": ", ds, screen)
		x = x + labelW + 2
	}
	if w.hasDate {
		yr, mo, dy := w.value.Year(), w.value.Month(), w.value.Day()
		for idx, vl := range fmt.Sprintf("%4d%2d%2d", yr, mo, dy) {
			if idx == 4 || idx == 7 {
				wh.DrawText(x, w.y, "-", ds, screen)
				x++
			}
			if idx == w.cursor && !w.nowBtnActive {
				if w.active {
					wh.DrawText(x, w.y, string(vl), ds.Reverse(true).Blink(true), screen)
				} else {
					wh.DrawText(x, w.y, string(vl), ds, screen)
				}
			} else {
				wh.DrawText(x, w.y, string(vl), ds, screen)
			}
			x++
		}
	}
	if w.hasTime {
		hr, mn, sc := w.value.Hour(), w.value.Minute(), w.value.Second()
		txt := fmt.Sprintf("%2d%2d", hr, mn)
		if w.hasSeconds {
			txt = fmt.Sprintf("%s%2d", txt, sc)
		}
		for idx, vl := range txt {
			if idx == 2 || idx == 5 {
				wh.DrawText(x, w.y, ":", ds, screen)
				x++
			}
			if idx+8 == w.cursor && !w.nowBtnActive {
				if w.active {
					wh.DrawText(x, w.y, string(vl), ds.Reverse(true).Blink(true), screen)
				} else {
					wh.DrawText(x, w.y, string(vl), ds, screen)
				}
			} else {
				wh.DrawText(x, w.y, string(vl), ds, screen)
			}
			x++
		}
	}
	if w.showNowBtn {
		if w.nowBtnActive {
			wh.DrawText(x, w.y, "[ Now ]", ds.Reverse(true), screen)
		} else {
			wh.DrawText(x, w.y, "[ Now ]", ds, screen)
		}
	}
}

func (w *TimeField) Active() bool       { return w.active }
func (w *TimeField) SetActive(a bool)   { w.active = a }
func (w *TimeField) Visible() bool      { return w.visible }
func (w *TimeField) SetVisible(a bool)  { w.visible = a }
func (w *TimeField) SetX(x int)         { w.x = x }
func (w *TimeField) SetY(y int)         { w.y = y }
func (w *TimeField) GetX() int          { return w.x }
func (w *TimeField) GetY() int          { return w.y }
func (w *TimeField) GetPos() Coord      { return Coord{X: w.x, Y: w.y} }
func (w *TimeField) SetPos(c Coord)     { w.x, w.y = c.X, c.Y }
func (w *TimeField) SetW(x int)         { w.w = x }
func (w *TimeField) SetH(y int)         { w.h = y }
func (w *TimeField) GetW() int          { return w.w }
func (w *TimeField) GetH() int          { return w.y }
func (w *TimeField) SetSize(c Coord)    { w.w, w.h = c.X, c.Y }
func (w *TimeField) Focusable() bool    { return true }
func (w *TimeField) SetTabbable(b bool) { w.tabbable = b }
func (w *TimeField) Tabbable() bool     { return w.tabbable }
func (w *TimeField) WantW() int {
	wdt := 0
	if w.hasDate {
		wdt = 10 // yyyy-mm-dd
	}
	if w.hasTime {
		if w.hasDate {
			wdt += 1 // space between date & time
		}
		if w.hasSeconds {
			wdt += 8 // hh:mm:ss
		} else {
			wdt += 5 // hh:mm
		}
	}
	return wdt
}
func (w *TimeField) WantH() int { return 1 }
func (w *TimeField) MinW() int {
	wdt := 0
	if w.hasDate {
		wdt = 10 // yyyy-mm-dd
	}
	if w.hasTime {
		if w.hasDate {
			wdt += 1 // space between date & time
		}
		if w.hasSeconds {
			wdt += 8 // hh:mm:ss
		} else {
			wdt += 5 // hh:mm
		}
	}
	return wdt
}
func (w *TimeField) MinH() int { return 1 }

func (w *TimeField) SetLabel(lbl string)  { w.label = lbl }
func (w *TimeField) SetTime(tm time.Time) { w.value = tm }

func (w *TimeField) SetHasSeconds(b bool) { w.hasSeconds = b }
func (w *TimeField) SetHasTime(b bool)    { w.hasTime = b }
func (w *TimeField) SetHasDate(b bool)    { w.hasDate = b }

func (w *TimeField) SetValue(v time.Time) { w.value = v }
func (w *TimeField) Value() time.Time     { return w.value }

func (w *TimeField) handleLeft(ev *tcell.EventKey) bool {
	if w.nowBtnActive {
		w.cursor = w.cursorLength()
		return true
	} else if w.cursor > 0 {
		w.cursor--
		return true
	}
	return false
}

func (w *TimeField) handleRight(ev *tcell.EventKey) bool {
	if w.cursor < w.cursorLength() {
		w.cursor++
		return true
	} else if !w.nowBtnActive {
		w.nowBtnActive = true
		return true
	}
	return false
}

func (w *TimeField) handleHome(ev *tcell.EventKey) bool {
	if w.cursor != 0 {
		w.cursor = 0
		return true
	}
	return false
}

func (w *TimeField) handleEnd(ev *tcell.EventKey) bool {
	l := w.cursorLength()
	if w.cursor != l {
		w.cursor = w.cursorLength()
		return true
	}
	return false
}

func (w *TimeField) cursorLength() int {
	var ret int
	if w.hasDate {
		ret += 8
	}
	if w.hasTime {
		ret += 4
		if w.hasSeconds {
			ret += 2
		}
	}
	return ret
}
