#include "ScreenManager.h"
#include "PopupWidget.h"
#include <algorithm>

ScreenManager* ScreenManager::_active = nullptr;

void ScreenManager::add( Widget* w ){
    _widgets.push_back( w );
	_zDirty = true;
    std::sort(_widgets.begin(), _widgets.end(),
        [](Widget* a, Widget* b) {
            return a->getZ() < b->getZ();
        });
}

void ScreenManager::activate(){
    
		if( _active == this ) return;

		if( _active ){
			
				for( auto* w : _active->_widgets ){
					w->clear();
					w->setScreenColor( _fillColor );
				}

			_pendingClearScreen = _active;
			_needsClearPass = true;
		}

    _active = this;

		for( auto* w : _widgets ){
			w->resume();
			w->setScreenColor( _fillColor );
		}
}

void ScreenManager::setActive(ScreenManager* s) {
    if (s) s->activate();
}

ScreenManager* ScreenManager::active() {
    return _active;
}

void ScreenManager::showModal( PopupWidget* p, uint16_t durationTime_ms ) {
	    
		if( _modal ){
			hideModal();
			return;
		}
    
	_modal = p;
    _modal->resume();
	_modalStartTime = millis();
	_modalDurationTime = durationTime_ms;
}

void ScreenManager::hideModal() {
    
		if( !_modal ) return;

    _modal->clear();
	_modal->setScreenColor( _fillColor );
	_pendingClearModal = _modal;
	_needsClearModal = true;
}


void ScreenManager::loop() {
	
		if( _needsClearPass && _pendingClearScreen ){

				for( auto* w : _pendingClearScreen->_widgets ) w->loop();

			_needsClearPass = false;
			_pendingClearScreen = nullptr;
			
				if( _modal ){
					hideModal();
				}
		}
		
		if( _needsClearModal && _pendingClearModal ){
			_pendingClearModal->loop();
			int16_t x = _pendingClearModal->x();
			int16_t y = _pendingClearModal->y();
			int16_t w = _pendingClearModal->w();
			int16_t h = _pendingClearModal->h();
			
				for( auto* widget : _widgets ){
						//Redraw - tylko widgety pod popupem
						if( widget->intersects( x, y, w, h ) ){
							widget->redraw();
						}
				}

			_pendingClearModal = nullptr;
			_needsClearModal = false;
			_modal = nullptr;
		}

		for( auto* w : _widgets ){
			w->loop();
		}

		if( _modal ){
			_modal->loop();
			
				if( _modalDurationTime ){
					uint32_t now = millis();
					
						if( now - _modalStartTime > _modalDurationTime ){
							hideModal();
						}
				}
		}
}