#pragma once
#include "Widget.h"

class PopupWidget : public Widget {
		char _text[96];
		int16_t x1 = 0, y1 = 0;
		uint16_t tw = 0, th = 0;
		uint8_t _textSize = 1, _padding = 10, _r = 0, _fgcl = 15, _bgcl = 0, _brcl = 15;
		bool _dirty = false, _needsMeasure = true;
		bool _widthAutoSize = false, _heightAutoSize = false, _xAutoPosition = false, _yAutoPosition = false;
		const GFXfont* font = nullptr;
		
		void measureText( int16_t* tx, int16_t* ty, uint16_t* tw, uint16_t* th ){
				
				if( _dsp == nullptr ) return;
			
			applyFont();
			_dsp->getTextBounds( _text, 0, 0, tx, ty, tw, th );
		}
		
		void measureSize( uint16_t* w, uint16_t* h ){
			uint16_t rw = *w, rh = *h;
			measureText( &x1, &y1, &tw, &th );
			
				if( _widthAutoSize ) rw = tw;
			
				if( _widthAutoSize ) rh = th;
				
			rw += (_padding*2);
			rh += (_padding*2);
			*w = rw;
			*h = rh;
		}
		
		void measurePosition( int16_t* x, int16_t* y ){
				
				if( _dsp == nullptr ) return;
				
			int16_t rx = *x, ry = *y;
			
				if( _xAutoPosition ) rx = (dsp->getDisplayWidth()-_w)/2;
				
				if( _yAutoPosition ) ry = (dsp->getDisplayHeight()-_h)/2;
				
			*x = rx;
			*y = ry;
		}
		
		void applyFont( void ){
			
				if( _dsp == nullptr ) return;
			
			_dsp->setFont( font );
		
				if( font == nullptr ) _dsp->setTextSize( _textSize );		
		}

	public:
		void setText( const char* t );
		void draw() override;
		
		void redraw( void ) override {
			_dirty = true;
		}
		
		void init( MyDisplay* dsp, uint16_t w=0, uint16_t h=0, int16_t x=-1, int16_t y=-1  ){
			
				if( dsp == nullptr ) return;
				
				if( w == 0 ) _widthAutoSize = true;
				if( h == 0 ) _heightAutoSize = true;
				if( x == -1 ) _xAutoPosition = true;
				if( y == -1 ) _yAutoPosition = true;

			Widget::init( dsp, x, y, w, h );
			_needsMeasure = true;
			_dirty = true;
			_initialized = true;
		}
		
		void setFont( const GFXfont* f ){
			font = f;
			_textSize = 1;
		}

		void setTextSize( uint8_t textSize ){
			_textSize = textSize;
		}
		
		void setPadding( uint8_t padding ){
			_padding = padding;
		}
		
		void setBRRadius( uint8_t r ){
			_r = r;
		}
		
		void setBRColor( uint8_t c ){
			_brcl = c;
		}
		
		void setBGColor( uint8_t c ){
			_bgcl = c;
		}
		
		void setFGColor( uint8_t c ){
			_fgcl = c;
		}
		
		void loop( void ){
			
				if( _needsMeasure ){
					measureSize( &_w, &_h );
					measurePosition( &_x, &_y );
					_needsMeasure = false;
				}
			
			Widget::loop();
		}
		
		void clear( bool resume_required = true ){
			Widget::clear( resume_required );
			_dirty = false;
		}
		
		void resume( void ){
			Widget::resume();
			_dirty = true;
		}
};

