classdef MatlabPathManager
    properties
        projectFileName = '.subpaths';
        stateFileName = '';
    end

    methods
        function obj = MatlabPathManager()

        end

        function p = stateFilePath(obj)
            p = fullfile(mpm.install_location(), obj.stateFileName);
        end

        % Load a given subpath into the state file and the matlab path and do savepath(), atomically
        function loadSubpath(obj, p)
            state = mpm.load_state();

            subpath = fullfile(pwd, p);
            addpath(subpath);
            state.added_paths(subpath) = true;

            mpm.save_state(state);

            % TODO: Make atomic + add savepath()
        end

        % Unload a given subpath from the state file and the matlab path and do savepath(), atomically
        function unloadSubpath(obj, p)
            state = mpm.load_state();

            subpath = fullfile(pwd, p);
            rmpath(subpath);
            state.added_paths.remove(subpath);

            mpm.save_state(state);

            % TODO: Make atomic + add savepath()
        end

        % Read project file in a folder and return cell array of all subpaths
        function sp = projectSubpaths(obj, projectFolder)
            try
                fstr = fileread(fullfile(projectFolder, obj.projectFileName));
            catch
                error('Subpath definition file ''%s'' not found.', obj.projectFileName);
            end
            sp = splitlines(strtrim(fstr));
        end

        function s = loadedSubpaths(obj)
            state = mpm.load_state();
            s = state.added_paths.keys();
            % TODO: Make it respect order from the matlab path
        end

        % Return all subpaths loaded into the matlab path, mimicing the order they appear there.
        function s = pathStatus(obj)
        end

        % Return all subpaths in the project and if they are active on the matlab path or not.
        function s = projectStatus(obj, projectFolder)
        end

        % Load all subpaths for a project
        function checkin(obj, projectFolder)
            sp = obj.projectSubpaths(projectFolder);

            for i = 1:length(sp)
                obj.loadSubpath(sp{i});
            end
        end

        % Unload all subpaths for a project
        function checkout(obj, projectFolder)
            sp = obj.projectSubpaths(projectFolder);

            for i = 1:length(sp)
                obj.unloadSubpath(sp{i});
            end
        end

        % Unload all loaded subpaths. The matlab path should be returned to it's original state
        function clear(obj)
            sp = obj.loadedSubpaths();

            for i = 1:length(sp)
                obj.unload(sp{i});
            end
        end
    end
end

% TODO: get rid of mpm.load_state and mpm.save_state
