classdef ImageViewer < handle
    
    properties
        loader;
        figureHandler;
        axisHandler;
    end
    
    methods
        function o = ImageViewer(loader)
            o.loader = loader;
        end
        
        function createFigure(o,varargin)
            o.figureHandler = figure;
            set(o.figureHandler,'WindowKeyPressFcn',{@o.callbackKeyPressed});
            set(o.figureHandler,'WindowButtonDownFcn',{@o.callbackImagePressed});
            
            set(o.figureHandler, varargin{:});
            
            o.axisHandler = gca;
        end
        
        function callbackKeyPressed(o,src,eventData)            
            if strcmp(eventData.Key,'rightarrow') 

                if strcmp(eventData.Modifier,'shift')
                    o.loader.jump(10);
                elseif strcmp(eventData.Modifier,'control')
                    o.loader.jump(100);
                else
                    o.loader.jump(1);
                end

                o.loader.load();
                o.draw();
                
            elseif strcmp(eventData.Key,'leftarrow')
                
                if strcmp(eventData.Modifier,'shift')
                    o.loader.jump(-10);
                elseif strcmp(eventData.Modifier,'control')
                    o.loader.jump(-100);
                else
                    o.loader.jump(-1);
                end
                
                o.loader.load();
                o.draw();
            end
        end
        
        function callbackImagePressed(o,src,eventData)
            % keyboard

            point = get(o.axisHandler, 'CurrentPoint');
            point = point(1,:); % get only the first line
            point = point -3;

            h = findobj(o.axisHandler,'Tag','pt'); % try to find the old point

            if ~isempty(h)
                delete(h);
            end
            
            % highlight the selected point
            hold on
            h = plot(o.axisHandler,point(1), point(2), 'r'); 
            set(h,'marker','+','linestyle','none','markersize',10);
            set(h,'MarkerFaceColor',[1 0 0],'markeredgecolor',[1 0 0])
            set(h,'Tag','pt'); % set its Tag property for later use   
        end
        
        function draw(o)
            o.axisHandler = cla(o.axisHandler);
            
            if isempty(o.loader.current_image)
                o.loader.load();
            end
            
            image(o.loader.current_image,'parent',o.axisHandler);
            set(o.axisHandler,'LooseInset',[0.05 0.05 0.05 0.05])
            axis equal
            set(o.axisHandler,'visible','off')
            
            h = text(10,15,['Frame: ' num2str(o.loader.current_frame)],'Parent',o.axisHandler);
            set(h,'FontSize',12,'FontWeight','bold','color',[1 1 1]) 
        end
        
    end
    
    
end