classdef mergeTool < matlab.apps.AppBase

    % Properties that correspond to app components
    properties (Access = public)
        UIFigure       matlab.ui.Figure
        GridLayout     matlab.ui.container.GridLayout
        GridLayout3    matlab.ui.container.GridLayout
        Label          matlab.ui.control.Label
        DropDown       matlab.ui.control.DropDown
        status         matlab.ui.control.Label
        generate       matlab.ui.control.Button
        heartGrid      matlab.ui.container.GridLayout
        line           matlab.ui.control.Label
        GridLayout2    matlab.ui.container.GridLayout
        currentPath    matlab.ui.control.EditField
        PathLabel      matlab.ui.control.Label
        addBtn         matlab.ui.control.Button
        selectFileBtn  matlab.ui.control.Button
    end

    
    properties (Access = private)
        legendField = {};    %Legend Field for each fig
        files = 0;           %Number of files
        values = {};         %All datapoints
        axis = {};           %Stores X/Y Axis labels
        subplotCnt = 1;      %Number of included
    end
    

    % Callbacks that handle component events
    methods (Access = private)

        % Code that executes after component creation
        function startupFcn(app)

            app.heartGrid.RowHeight{1} = "fit";
            app.heartGrid.RowHeight{2} = "fit";
            
            %Add X-Axis Label
            channelLabel = uilabel(app.heartGrid);                         
            channelLabel.Text = "X-Axis Label:";
            channelLabel.FontSize = 12;
            channelLabel.HorizontalAlignment = 'right';
            channelLabel.Layout.Row = 1;  
            channelLabel.Layout.Column = 1;

            choose = uieditfield(app.heartGrid);
            choose.Value = 'Time[s]';
            choose.Layout.Row = 1;
            choose.Layout.Column = 2;
            app.axis{1} = choose;

            %Add Y-Axis name
            channelLabel = uilabel(app.heartGrid);                         
            channelLabel.Text = "Y-Axis Label:";
            channelLabel.FontSize = 12;
            channelLabel.HorizontalAlignment = 'right';
            channelLabel.Layout.Row = 1;  
            channelLabel.Layout.Column = 3;

            choose = uieditfield(app.heartGrid);
            choose.Value =  'degree celsius [°C]';
            choose.Layout.Row = 1;
            choose.Layout.Column = 4;
            app.axis{2} = choose;
            
        end

        % Button pushed function: selectFileBtn
        function selectFileBtnButtonPushed(app, event)
            try
                %Open file dialog and get path
                [baseName, folder] = uigetfile('*.fig');
                selpath = fullfile(folder, baseName);
                app.currentPath.Value = selpath;
            catch exception
                app.status.Text = exception.message;
            end
        end

        % Button pushed function: generate
        function generateButtonPushed(app, event)
            %Deactivate buttons and set busy text
            app.status.Text = 'Status: BUSY - Generating plot';
            app.addBtn.Enable = "off";
            app.generate.Enable = "off";
            
            for file=1: app.files
                app.legendField{file + 1}.Enable = "off";
            end      
            drawnow
            
            %get saving location
            try
                %Open file dialog and get path
                selpath = uigetdir('C:\');
            catch exception
                app.status.Text = exception.message;
            end

            %Generate figure
            figure(1)
            ylabel(app.axis{2}.Value);
            xlabel(app.axis{1}.Value);
            hold on

            %dumb workaround for MATLAB not accepting strings
            legendEntries(1) = "Test";

            % support different subplot configs
            if app.DropDown.Value == "No Subplot"

                for file=1: app.files
                    app.legendField{app.files + 1}.Enable = "off";
                    plot(app.values{file + 1}{1}, app.values{file + 1}{2});
                    legendEntries(file) = append("",app.legendField{file + 1}.Value);
                end      

                legend(legendEntries(1:end));

            elseif app.DropDown.Value == "Subplot Version A"
                
                if app.files == 2
                    app.legendField{2}.Enable = "off";
                    subplot(2,1,1)
                    plot(app.values{2}{1}, app.values{2}{2});
                    title(append("",app.legendField{2}.Value));
                    xlabel(app.axis{1}.Value);
                    
                    app.legendField{3}.Enable = "off";
                    subplot(2,1,2)
                    plot(app.values{3}{1}, app.values{3}{2});
                    title(append("",app.legendField{3}.Value));
                    xlabel(app.axis{1}.Value);

                elseif app.files == 3
                    app.legendField{2}.Enable = "off";
                    subplot(2,2,1)
                    plot(app.values{2}{1}, app.values{2}{2});
                    title(append("",app.legendField{2}.Value));
                    xlabel(app.axis{1}.Value);

                    app.legendField{3}.Enable = "off";
                    subplot(2,2,2)
                    plot(app.values{3}{1}, app.values{3}{2});
                    title(append("",app.legendField{3}.Value));
                    xlabel(app.axis{1}.Value);

                    app.legendField{4}.Enable = "off";
                    subplot(2,2,[3,4])
                    plot(app.values{4}{1}, app.values{4}{2});
                    title(append("",app.legendField{4}.Value));
                    xlabel(app.axis{1}.Value);

                elseif app.files == 4
                    app.legendField{2}.Enable = "off";
                    subplot(2,2,1)
                    plot(app.values{2}{1}, app.values{2}{2});
                    title(append("",app.legendField{2}.Value));
                    xlabel(app.axis{1}.Value);

                    app.legendField{3}.Enable = "off";
                    subplot(2,2,2)
                    plot(app.values{3}{1}, app.values{3}{2});
                    title(append("",app.legendField{3}.Value));
                    xlabel(app.axis{1}.Value);

                    app.legendField{4}.Enable = "off";
                    subplot(2,2,3)
                    plot(app.values{4}{1}, app.values{4}{2});
                    title(append("",app.legendField{4}.Value));
                    xlabel(app.axis{1}.Value);

                    app.legendField{5}.Enable = "off";
                    subplot(2,2,4)
                    plot(app.values{5}{1}, app.values{5}{2});
                    title(append("",app.legendField{5}.Value));
                    xlabel(app.axis{1}.Value);
                end

            elseif app.DropDown.Value == "Subplot Version B"
                if app.files == 2
                    app.legendField{2}.Enable = "off";
                    subplot(1,2,1)
                    plot(app.values{2}{1}, app.values{2}{2});
                    title(append("",app.legendField{2}.Value));
                    xlabel(app.axis{1}.Value);
                    
                    app.legendField{3}.Enable = "off";
                    subplot(1,2,2)
                    plot(app.values{3}{1}, app.values{3}{2});
                    title(append("",app.legendField{3}.Value));
                    xlabel(app.axis{1}.Value);

                elseif app.files == 3
                    app.legendField{2}.Enable = "off";
                    subplot(2,2,1)
                    plot(app.values{2}{1}, app.values{2}{2});
                    title(append("",app.legendField{2}.Value));
                    xlabel(app.axis{1}.Value);

                    app.legendField{3}.Enable = "off";
                    subplot(2,2,[2,4])
                    plot(app.values{3}{1}, app.values{3}{2});
                    title(append("",app.legendField{3}.Value));
                    xlabel(app.axis{1}.Value);

                    app.legendField{4}.Enable = "off";
                    subplot(2,2,3)
                    plot(app.values{4}{1}, app.values{4}{2});
                    title(append("",app.legendField{4}.Value));
                    xlabel(app.axis{1}.Value);

                elseif app.files == 4
                    app.legendField{2}.Enable = "off";
                    subplot(2,3,1)
                    plot(app.values{2}{1}, app.values{2}{2});
                    title(append("",app.legendField{2}.Value));
                    xlabel(app.axis{1}.Value);

                    app.legendField{3}.Enable = "off";
                    subplot(2,3,2)
                    plot(app.values{3}{1}, app.values{3}{2});
                    title(append("",app.legendField{3}.Value));
                    xlabel(app.axis{1}.Value);

                    app.legendField{4}.Enable = "off";
                    subplot(2,3,3)
                    plot(app.values{4}{1}, app.values{4}{2});
                    title(append("",app.legendField{4}.Value));
                    xlabel(app.axis{1}.Value);

                    app.legendField{5}.Enable = "off";
                    subplot(2,3,[4,5,6])
                    plot(app.values{5}{1}, app.values{5}{2});
                    title(append("",app.legendField{5}.Value));
                    xlabel(app.axis{1}.Value);
                end

            end

            %Save plot
            %Suppress the warnings. If not where would be a lot of warnings
            %because of the creation of folders that already exist
            warning('off','all');   
        
            %Create path for saving and save as .fig and .png
            savefig(figure(1), strcat(strcat(selpath, '\',"merged"), '.fig'));
            saveas(figure(1), strcat(strcat(selpath, '\',"merged"), '.png'));
        
            %Turn warning back on
            warning('on','all')

            hold off

            %Reactivate buttons
            app.status.Text = 'Status: Ready';
            app.addBtn.Enable = "on";
            app.generate.Enable = "on";
            
            for file=1: app.files
                app.legendField{file + 1}.Enable = "on";
            end      
            drawnow
        end

        % Button pushed function: addBtn
        function addBtnButtonPushed(app, event)
            %Deactivate buttons and set busy text
            app.status.Text = 'Status: BUSY - Load data';
            app.addBtn.Enable = "off";
            app.generate.Enable = "off";
            drawnow

            % load data from fig file
            try
                fig = openfig(app.currentPath.Value);
                fig = gcf;
            catch
                %Reactivate buttons
                app.status.Text = 'Status: Ready';
                app.addBtn.Enable = "on";
                app.generate.Enable = "on";
                drawnow

                msgbox("Error reading file")
                return
            end

            app.files = app.files + 1 ;
            data = {};

            dataObjs = findobj(fig,'-property','XData');
            data{1} = dataObjs(1).XData;

            dataObjs = findobj(fig,'-property','YData');
            data{2} = dataObjs(1).YData;

            dataObjs = findobj(fig,'type','axe');
            data{3} =get(get(dataObjs,'xlabel'),'string');

            %close file
            close(gcf)

            app.values{app.files + 1} = data;

            %Get file name
            [~,name,ext] = fileparts(app.currentPath.Value);
            fileName = append(name,ext);

            app.heartGrid.RowHeight{app.files + 1} = "fit";

            %Add Number
            fileNumber = uilabel(app.heartGrid);
            fileNumber.Text = sprintf('%d.',app.files);
            fileNumber.Layout.Row = app.files + 1;
            fileNumber.Layout.Column = 1;
            fileNumber.FontSize = 15;

            %Add label
            fileLabel = uilabel(app.heartGrid);
            fileLabel.Text = fileName;
            fileLabel.Layout.Row = app.files + 1;
            fileLabel.Layout.Column = 2;
            fileLabel.FontSize = 15;
            fileLabel.FontWeight = 'bold';

            %Add Legend name
            channelLabel = uilabel(app.heartGrid);                         
            channelLabel.Text = "Name in Legend: ";
            channelLabel.FontSize = 12;
            channelLabel.HorizontalAlignment = 'right';
            channelLabel.Layout.Row = app.files + 1;  
            channelLabel.Layout.Column = 3;

            choose = uieditfield(app.heartGrid);
            choose.Value = fileName;
            choose.Layout.Row = app.files + 1;
            choose.Layout.Column = 4;
            app.legendField{app.files + 1} = choose;

            %Reactivate buttons
            app.status.Text = 'Status: Ready';
            app.addBtn.Enable = "on";
            app.generate.Enable = "on";
            drawnow
        end
    end

    % Component initialization
    methods (Access = private)

        % Create UIFigure and components
        function createComponents(app)

            % Create UIFigure and hide until all components are created
            app.UIFigure = uifigure('Visible', 'off');
            app.UIFigure.Position = [100 100 640 480];
            app.UIFigure.Name = 'MATLAB App';

            % Create GridLayout
            app.GridLayout = uigridlayout(app.UIFigure);
            app.GridLayout.ColumnWidth = {'1x'};
            app.GridLayout.RowHeight = {'fit', 'fit', '1x', 'fit'};
            app.GridLayout.Scrollable = 'on';

            % Create GridLayout2
            app.GridLayout2 = uigridlayout(app.GridLayout);
            app.GridLayout2.ColumnWidth = {'fit', 'fit', '1x', 'fit', 'fit'};
            app.GridLayout2.RowHeight = {'1x'};
            app.GridLayout2.Layout.Row = 1;
            app.GridLayout2.Layout.Column = 1;

            % Create selectFileBtn
            app.selectFileBtn = uibutton(app.GridLayout2, 'push');
            app.selectFileBtn.ButtonPushedFcn = createCallbackFcn(app, @selectFileBtnButtonPushed, true);
            app.selectFileBtn.FontSize = 15;
            app.selectFileBtn.Layout.Row = 1;
            app.selectFileBtn.Layout.Column = 1;
            app.selectFileBtn.Text = 'Select File';

            % Create addBtn
            app.addBtn = uibutton(app.GridLayout2, 'push');
            app.addBtn.ButtonPushedFcn = createCallbackFcn(app, @addBtnButtonPushed, true);
            app.addBtn.FontSize = 15;
            app.addBtn.Layout.Row = 1;
            app.addBtn.Layout.Column = 5;
            app.addBtn.Text = 'Add';

            % Create PathLabel
            app.PathLabel = uilabel(app.GridLayout2);
            app.PathLabel.HorizontalAlignment = 'right';
            app.PathLabel.Layout.Row = 1;
            app.PathLabel.Layout.Column = 2;
            app.PathLabel.Text = 'Path:';

            % Create currentPath
            app.currentPath = uieditfield(app.GridLayout2, 'text');
            app.currentPath.Placeholder = 'C:\Users\max_h\Desktop\Testkampagne\data\coldflow\Data\STACF\02';
            app.currentPath.Layout.Row = 1;
            app.currentPath.Layout.Column = 3;
            app.currentPath.Value = 'C:\';

            % Create line
            app.line = uilabel(app.GridLayout);
            app.line.BackgroundColor = [0 0 0];
            app.line.FontSize = 0.3;
            app.line.Layout.Row = 2;
            app.line.Layout.Column = 1;

            % Create heartGrid
            app.heartGrid = uigridlayout(app.GridLayout);
            app.heartGrid.ColumnWidth = {'1x'};
            app.heartGrid.RowHeight = {'1x'};
            app.heartGrid.Layout.Row = 3;
            app.heartGrid.Layout.Column = 1;
            app.heartGrid.Scrollable = 'on';

            % Create GridLayout3
            app.GridLayout3 = uigridlayout(app.GridLayout);
            app.GridLayout3.ColumnWidth = {'1.5x', '1x', '1x'};
            app.GridLayout3.RowHeight = {'1x'};
            app.GridLayout3.Layout.Row = 4;
            app.GridLayout3.Layout.Column = 1;

            % Create generate
            app.generate = uibutton(app.GridLayout3, 'push');
            app.generate.ButtonPushedFcn = createCallbackFcn(app, @generateButtonPushed, true);
            app.generate.Enable = 'off';
            app.generate.Layout.Row = 1;
            app.generate.Layout.Column = 3;
            app.generate.Text = 'Generate Merged Plot';

            % Create status
            app.status = uilabel(app.GridLayout3);
            app.status.VerticalAlignment = 'bottom';
            app.status.Layout.Row = 1;
            app.status.Layout.Column = 1;
            app.status.Text = 'Developed by Space Team Aachen e.V.';

            % Create DropDown
            app.DropDown = uidropdown(app.GridLayout3);
            app.DropDown.Items = {'No Subplot', 'Subplot Version A', 'Subplot Version B'};
            app.DropDown.Layout.Row = 1;
            app.DropDown.Layout.Column = 2;
            app.DropDown.Value = 'No Subplot';

            % Create Label
            app.Label = uilabel(app.GridLayout3);
            app.Label.HorizontalAlignment = 'right';
            app.Label.Layout.Row = 1;
            app.Label.Layout.Column = 1;
            app.Label.Text = '';

            % Show the figure after all components are created
            app.UIFigure.Visible = 'on';
        end
    end

    % App creation and deletion
    methods (Access = public)

        % Construct app
        function app = mergeTool

            % Create UIFigure and components
            createComponents(app)

            % Register the app with App Designer
            registerApp(app, app.UIFigure)

            % Execute the startup function
            runStartupFcn(app, @startupFcn)

            if nargout == 0
                clear app
            end
        end

        % Code that executes before app deletion
        function delete(app)

            % Delete UIFigure when app is deleted
            delete(app.UIFigure)
        end
    end
end