package vt10x

import (
	
	
	
)

const (
	tabspaces = 8
)

const (
	attrReverse = 1 << iota
	attrUnderline
	attrBold
	attrGfx
	attrItalic
	attrBlink
	attrWrap
)

const (
	cursorDefault = 1 << iota
	cursorWrapNext
	cursorOrigin
)

// ModeFlag represents various terminal mode states.
type ModeFlag uint32

// Terminal modes
const (
	ModeWrap ModeFlag = 1 << iota
	ModeInsert
	ModeAppKeypad
	ModeAltScreen
	ModeCRLF
	ModeMouseButton
	ModeMouseMotion
	ModeReverse
	ModeKeyboardLock
	ModeHide
	ModeEcho
	ModeAppCursor
	ModeMouseSgr
	Mode8bit
	ModeBlink
	ModeFBlink
	ModeFocus
	ModeMouseX10
	ModeMouseMany
	ModeMouseMask = ModeMouseButton | ModeMouseMotion | ModeMouseX10 | ModeMouseMany
)

// ChangeFlag represents possible state changes of the terminal.
type ChangeFlag uint32

// Terminal changes to occur in VT.ReadState
const (
	ChangedScreen ChangeFlag = 1 << iota
	ChangedTitle
)

type Glyph struct {
	Char   rune
	Mode   int16
	FG, BG Color
}

type line []Glyph

type Cursor struct {
	Attr  Glyph
	X, Y  int
	State uint8
}

type parseState func(c rune)

// State represents the terminal emulation state. Use Lock/Unlock
// methods to synchronize data access with VT.
type State struct {
	DebugLogger *log.Logger

	w             io.Writer
	mu            sync.Mutex
	changed       ChangeFlag
	cols, rows    int
	lines         []line
	altLines      []line
	dirty         []bool // line dirtiness
	anydirty      bool
	cur, curSaved Cursor
	top, bottom   int // scroll limits
	mode          ModeFlag
	state         parseState
	str           strEscape
	csi           csiEscape
	numlock       bool
	tabs          []bool
	title         string
	colorOverride map[Color]Color
}

func newState( io.Writer) *State {
	return &State{
		w:             ,
		colorOverride: make(map[Color]Color),
	}
}

func ( *State) ( string,  ...interface{}) {
	if .DebugLogger != nil {
		.DebugLogger.Printf(, ...)
	}
}

func ( *State) ( string) {
	if .DebugLogger != nil {
		.DebugLogger.Println()
	}
}

func ( *State) () {
	.mu.Lock()
}

func ( *State) () {
	.mu.Unlock()
}

// Lock locks the state object's mutex.
func ( *State) () {
	.mu.Lock()
}

// Unlock resets change flags and unlocks the state object's mutex.
func ( *State) () {
	.resetChanges()
	.mu.Unlock()
}

// Cell returns the glyph containing the character code, foreground color, and
// background color at position (x, y) relative to the top left of the terminal.
func ( *State) (,  int) Glyph {
	 := .lines[][]
	,  := .colorOverride[.FG]
	if  {
		.FG = 
	}
	,  := .colorOverride[.BG]
	if  {
		.BG = 
	}
	return 
}

// Cursor returns the current position of the cursor.
func ( *State) () Cursor {
	return .cur
}

// CursorVisible returns the visible state of the cursor.
func ( *State) () bool {
	return .mode&ModeHide == 0
}

// Mode returns the current terminal mode.
func ( *State) () ModeFlag {
	return .mode
}

// Title returns the current title set via the tty.
func ( *State) () string {
	return .title
}

/*
// ChangeMask returns a bitfield of changes that have occured by VT.
func (t *State) ChangeMask() ChangeFlag {
	return t.changed
}
*/

// Changed returns true if change has occured.
func ( *State) ( ChangeFlag) bool {
	return .changed& != 0
}

// resetChanges resets the change mask and dirtiness.
func ( *State) () {
	for  := range .dirty {
		.dirty[] = false
	}
	.anydirty = false
	.changed = 0
}

func ( *State) () {
	.curSaved = .cur
}

func ( *State) () {
	.cur = .curSaved
	.moveTo(.cur.X, .cur.Y)
}

func ( *State) ( rune) {
	.state()
}

func ( *State) ( bool) {
	 := .cur.X
	if  {
		if  == .cols {
			return
		}
		for ++;  < .cols && !.tabs[]; ++ {
		}
	} else {
		if  == 0 {
			return
		}
		for --;  > 0 && !.tabs[]; -- {
		}
	}
	.moveTo(, .cur.Y)
}

func ( *State) ( bool) {
	 := .cur.Y
	if  == .bottom {
		 := .cur
		.cur = .defaultCursor()
		.scrollUp(.top, 1)
		.cur = 
	} else {
		++
	}
	if  {
		.moveTo(0, )
	} else {
		.moveTo(.cur.X, )
	}
}

// table from st, which in turn is from rxvt :)
var gfxCharTable = [62]rune{
	'↑', '↓', '→', '←', '█', '▚', '☃', // A - G
	0, 0, 0, 0, 0, 0, 0, 0, // H - O
	0, 0, 0, 0, 0, 0, 0, 0, // P - W
	0, 0, 0, 0, 0, 0, 0, ' ', // X - _
	'◆', '▒', '␉', '␌', '␍', '␊', '°', '±', // ` - g
	'␤', '␋', '┘', '┐', '┌', '└', '┼', '⎺', // h - o
	'⎻', '─', '⎼', '⎽', '├', '┤', '┴', '┬', // p - w
	'│', '≤', '≥', 'π', '≠', '£', '·', // x - ~
}

func ( *State) ( rune,  *Glyph, ,  int) {
	if .Mode&attrGfx != 0 {
		if  >= 0x41 &&  <= 0x7e && gfxCharTable[-0x41] != 0 {
			 = gfxCharTable[-0x41]
		}
	}
	.changed |= ChangedScreen
	.dirty[] = true
	.lines[][] = *
	.lines[][].Char = 
	//if t.options.BrightBold && attr.Mode&attrBold != 0 && attr.FG < 8 {
	if .Mode&attrBold != 0 && .FG < 8 {
		.lines[][].FG = .FG + 8
	}
	if .Mode&attrReverse != 0 {
		.lines[][].FG = .BG
		.lines[][].BG = .FG
	}
}

func ( *State) () Cursor {
	 := Cursor{}
	.Attr.FG = DefaultFG
	.Attr.BG = DefaultBG
	return 
}

func ( *State) () {
	.cur = .defaultCursor()
	.saveCursor()
	for  := range .tabs {
		.tabs[] = false
	}
	for  := tabspaces;  < len(.tabs);  += tabspaces {
		.tabs[] = true
	}
	.top = 0
	.bottom = .rows - 1
	.mode = ModeWrap
	.clear(0, 0, .rows-1, .cols-1)
	.moveTo(0, 0)
}

// TODO: definitely can improve allocs
func ( *State) (,  int) bool {
	if  == .cols &&  == .rows {
		return false
	}
	if  < 1 ||  < 1 {
		return false
	}
	 := .cur.Y -  + 1
	if  > 0 {
		copy(.lines, .lines[:+])
		copy(.altLines, .altLines[:+])
	}

	, ,  := .lines, .altLines, .tabs
	.lines = make([]line, )
	.altLines = make([]line, )
	.dirty = make([]bool, )
	.tabs = make([]bool, )

	 := min(, .rows)
	 := min(, .cols)
	.changed |= ChangedScreen
	for  := 0;  < ; ++ {
		.dirty[] = true
		.lines[] = make(line, )
		.altLines[] = make(line, )
	}
	for  := 0;  < ; ++ {
		copy(.lines[], [])
		copy(.altLines[], [])
	}
	copy(.tabs, )
	if  > .cols {
		 := .cols - 1
		for  > 0 && ![] {
			--
		}
		for  += tabspaces;  < len();  += tabspaces {
			[] = true
		}
	}

	.cols = 
	.rows = 
	.setScroll(0, -1)
	.moveTo(.cur.X, .cur.Y)
	for  := 0;  < 2; ++ {
		if  <  &&  > 0 {
			.clear(, 0, -1, -1)
		}
		if  > 0 &&  <  {
			.clear(0, , -1, -1)
		}
		.swapScreen()
	}
	return  > 0
}

func ( *State) (, , ,  int) {
	if  >  {
		,  = , 
	}
	if  >  {
		,  = , 
	}
	 = clamp(, 0, .cols-1)
	 = clamp(, 0, .cols-1)
	 = clamp(, 0, .rows-1)
	 = clamp(, 0, .rows-1)
	.changed |= ChangedScreen
	for  := ;  <= ; ++ {
		.dirty[] = true
		for  := ;  <= ; ++ {
			.lines[][] = .cur.Attr
			.lines[][].Char = ' '
		}
	}
}

func ( *State) () {
	.clear(0, 0, .cols-1, .rows-1)
}

func ( *State) (,  int) {
	if .cur.State&cursorOrigin != 0 {
		 += .top
	}
	.moveTo(, )
}

func ( *State) (,  int) {
	var ,  int
	if .cur.State&cursorOrigin != 0 {
		 = .top
		 = .bottom
	} else {
		 = 0
		 = .rows - 1
	}
	 = clamp(, 0, .cols-1)
	 = clamp(, , )
	.changed |= ChangedScreen
	.cur.State &^= cursorWrapNext
	.cur.X = 
	.cur.Y = 
}

func ( *State) () {
	.lines, .altLines = .altLines, .lines
	.mode ^= ModeAltScreen
	.dirtyAll()
}

func ( *State) () {
	.changed |= ChangedScreen
	for  := 0;  < .rows; ++ {
		.dirty[] = true
	}
}

func ( *State) (,  int) {
	 = clamp(, 0, .rows-1)
	 = clamp(, 0, .rows-1)
	if  >  {
		,  = , 
	}
	.top = 
	.bottom = 
}

func min(,  int) int {
	if  <  {
		return 
	}
	return 
}

func max(,  int) int {
	if  >  {
		return 
	}
	return 
}

func clamp(, ,  int) int {
	if  <  {
		return 
	} else if  >  {
		return 
	}
	return 
}

func between(, ,  int) bool {
	if  <  ||  >  {
		return false
	}
	return true
}

func ( *State) (,  int) {
	 = clamp(, 0, .bottom-+1)
	.clear(0, .bottom-+1, .cols-1, .bottom)
	.changed |= ChangedScreen
	for  := .bottom;  >= +; -- {
		.lines[], .lines[-] = .lines[-], .lines[]
		.dirty[] = true
		.dirty[-] = true
	}

	// TODO: selection scroll
}

func ( *State) (,  int) {
	 = clamp(, 0, .bottom-+1)
	.clear(0, , .cols-1, +-1)
	.changed |= ChangedScreen
	for  := ;  <= .bottom-; ++ {
		.lines[], .lines[+] = .lines[+], .lines[]
		.dirty[] = true
		.dirty[+] = true
	}

	// TODO: selection scroll
}

func ( *State) ( bool,  ModeFlag) {
	if  {
		.mode |= 
	} else {
		.mode &^= 
	}
}

func ( *State) ( bool,  bool,  []int) {
	if  {
		for ,  := range  {
			switch  {
			case 1: // DECCKM - cursor key
				.modMode(, ModeAppCursor)
			case 5: // DECSCNM - reverse video
				 := .mode
				.modMode(, ModeReverse)
				if  != .mode {
					// TODO: redraw
				}
			case 6: // DECOM - origin
				if  {
					.cur.State |= cursorOrigin
				} else {
					.cur.State &^= cursorOrigin
				}
				.moveAbsTo(0, 0)
			case 7: // DECAWM - auto wrap
				.modMode(, ModeWrap)
			// IGNORED:
			case 0, // error
				2,  // DECANM - ANSI/VT52
				3,  // DECCOLM - column
				4,  // DECSCLM - scroll
				8,  // DECARM - auto repeat
				18, // DECPFF - printer feed
				19, // DECPEX - printer extent
				42, // DECNRCM - national characters
				12: // att610 - start blinking cursor
				break
			case 25: // DECTCEM - text cursor enable mode
				.modMode(!, ModeHide)
			case 9: // X10 mouse compatibility mode
				.modMode(false, ModeMouseMask)
				.modMode(, ModeMouseX10)
			case 1000: // report button press
				.modMode(false, ModeMouseMask)
				.modMode(, ModeMouseButton)
			case 1002: // report motion on button press
				.modMode(false, ModeMouseMask)
				.modMode(, ModeMouseMotion)
			case 1003: // enable all mouse motions
				.modMode(false, ModeMouseMask)
				.modMode(, ModeMouseMany)
			case 1004: // send focus events to tty
				.modMode(, ModeFocus)
			case 1006: // extended reporting mode
				.modMode(, ModeMouseSgr)
			case 1034:
				.modMode(, Mode8bit)
			case 1049, // = 1047 and 1048
				47, 1047:
				 := .mode&ModeAltScreen != 0
				if  {
					.clear(0, 0, .cols-1, .rows-1)
				}
				if ! || ! {
					.swapScreen()
				}
				if  != 1049 {
					break
				}
				fallthrough
			case 1048:
				if  {
					.saveCursor()
				} else {
					.restoreCursor()
				}
			case 1001:
				// mouse highlight mode; can hang the terminal by design when
				// implemented
			case 1005:
				// utf8 mouse mode; will confuse applications not supporting
				// utf8 and luit
			case 1015:
				// urxvt mangled mouse mode; incompatiblt and can be mistaken
				// for other control codes
			default:
				.logf("unknown private set/reset mode %d\n", )
			}
		}
	} else {
		for ,  := range  {
			switch  {
			case 0: // Error (ignored)
			case 2: // KAM - keyboard action
				.modMode(, ModeKeyboardLock)
			case 4: // IRM - insertion-replacement
				.modMode(, ModeInsert)
				.logln("insert mode not implemented")
			case 12: // SRM - send/receive
				.modMode(, ModeEcho)
			case 20: // LNM - linefeed/newline
				.modMode(, ModeCRLF)
			case 34:
				.logln("right-to-left mode not implemented")
			case 96:
				.logln("right-to-left copy mode not implemented")
			default:
				.logf("unknown set/reset mode %d\n", )
			}
		}
	}
}

func ( *State) ( []int) {
	if len() == 0 {
		 = []int{0}
	}
	for  := 0;  < len(); ++ {
		 := []
		switch  {
		case 0:
			.cur.Attr.Mode &^= attrReverse | attrUnderline | attrBold | attrItalic | attrBlink
			.cur.Attr.FG = DefaultFG
			.cur.Attr.BG = DefaultBG
		case 1:
			.cur.Attr.Mode |= attrBold
		case 3:
			.cur.Attr.Mode |= attrItalic
		case 4:
			.cur.Attr.Mode |= attrUnderline
		case 5, 6: // slow, rapid blink
			.cur.Attr.Mode |= attrBlink
		case 7:
			.cur.Attr.Mode |= attrReverse
		case 21, 22:
			.cur.Attr.Mode &^= attrBold
		case 23:
			.cur.Attr.Mode &^= attrItalic
		case 24:
			.cur.Attr.Mode &^= attrUnderline
		case 25, 26:
			.cur.Attr.Mode &^= attrBlink
		case 27:
			.cur.Attr.Mode &^= attrReverse
		case 38:
			if +2 < len() && [+1] == 5 {
				 += 2
				if between([], 0, 255) {
					.cur.Attr.FG = Color([])
				} else {
					.logf("bad fgcolor %d\n", [])
				}
			} else if +4 < len() && [+1] == 2 {
				 += 4
				, ,  := [-2], [-1], []
				if !between(, 0, 255) || !between(, 0, 255) || !between(, 0, 255) {
					.logf("bad fg rgb color (%d,%d,%d)\n", , , )
				} else {
					.cur.Attr.FG = Color(<<16 | <<8 | )
				}
			} else {
				.logf("gfx attr %d unknown\n", )
			}
		case 39:
			.cur.Attr.FG = DefaultFG
		case 48:
			if +2 < len() && [+1] == 5 {
				 += 2
				if between([], 0, 255) {
					.cur.Attr.BG = Color([])
				} else {
					.logf("bad bgcolor %d\n", [])
				}
			} else if +4 < len() && [+1] == 2 {
				 += 4
				, ,  := [-2], [-1], []
				if !between(, 0, 255) || !between(, 0, 255) || !between(, 0, 255) {
					.logf("bad bg rgb color (%d,%d,%d)\n", , , )
				} else {
					.cur.Attr.BG = Color(<<16 | <<8 | )
				}
			} else {
				.logf("gfx attr %d unknown\n", )
			}
		case 49:
			.cur.Attr.BG = DefaultBG
		default:
			if between(, 30, 37) {
				.cur.Attr.FG = Color( - 30)
			} else if between(, 40, 47) {
				.cur.Attr.BG = Color( - 40)
			} else if between(, 90, 97) {
				.cur.Attr.FG = Color( - 90 + 8)
			} else if between(, 100, 107) {
				.cur.Attr.BG = Color( - 100 + 8)
			} else {
				.logf("gfx attr %d unknown\n", )
			}
		}
	}
}

func ( *State) ( int) {
	 := .cur.X
	 :=  + 
	 := .cols - 
	.changed |= ChangedScreen
	.dirty[.cur.Y] = true

	if  >= .cols {
		.clear(.cur.X, .cur.Y, .cols-1, .cur.Y)
	} else {
		copy(.lines[.cur.Y][:+], .lines[.cur.Y][:+])
		.clear(, .cur.Y, -1, .cur.Y)
	}
}

func ( *State) ( int) {
	if .cur.Y < .top || .cur.Y > .bottom {
		return
	}
	.scrollDown(.cur.Y, )
}

func ( *State) ( int) {
	if .cur.Y < .top || .cur.Y > .bottom {
		return
	}
	.scrollUp(.cur.Y, )
}

func ( *State) ( int) {
	 := .cur.X + 
	 := .cur.X
	 := .cols - 
	.changed |= ChangedScreen
	.dirty[.cur.Y] = true

	if  >= .cols {
		.clear(.cur.X, .cur.Y, .cols-1, .cur.Y)
	} else {
		copy(.lines[.cur.Y][:+], .lines[.cur.Y][:+])
		.clear(.cols-, .cur.Y, .cols-1, .cur.Y)
	}
}

func ( *State) ( string) {
	.changed |= ChangedTitle
	.title = 
}

func ( *State) () (,  int) {
	return .cols, .rows
}

func ( *State) () string {
	.Lock()
	defer .Unlock()

	var  []rune
	for  := 0;  < .rows; ++ {
		for  := 0;  < .cols; ++ {
			 := .Cell(, )
			 = append(, .Char)
		}
		 = append(, '\n')
	}

	return string()
}