classdef Xb3Loader < handle
    
    properties
        main_path;
        files;
        ids;
        current_frame;
        current_image;
    end
    
    methods
        
        function o = Xb3Loader(main_path)
            o.main_path = main_path;
            o.files = dir(fullfile(main_path,'*.png'));
            
            o.ids = zeros(length(o.files),1);
            
            for i=1:length(o.files)
                file_name = o.files(i).name;
                file_id = str2double(file_name(1:end-4));
                o.ids(i) = file_id;
            end
            
            o.ids = sort(o.ids);
            
            o.current_frame = o.min();
        end
        
        function v = min(o)
            v = min(o.ids);
        end
        
        function v = max(o)
            v = max(o.ids);
        end
        
        function setCurrentFrame(o,id)
            pos = find(o.ids == id,1);
            
            if isempty(pos)
                warning(['File with id ' num2str(id) ' does not exists.'])
                return
            end
            
            o.current_frame = id;
        end
        
        function result = increment(o,value)
            
            next_value = o.current_frame + value;
            
            %Check if the value exists in the list
            pos = find(o.ids == next_value,1);
            
            if ~isempty(pos)
                o.current_frame = next_value;
                result = true;
            else
                warning(['Frame id ' num2str(next_value) ' does not exists'])
                result = false;
            end
        end
        
        function im = load(o)
            
            pos = find(o.ids == o.current_frame,1);
            
            if isempty(pos)
                warning(['File with id ' num2str(o.current_frame) ' does not exists.'])
                o.current_image=[];
                im = o.current_image;
                return
            end
            
            file_name = o.files(pos).name;
            
            o.current_image = imread(fullfile(o.main_path,file_name));
            im = o.current_image;
        end
    
    end
end
