classdef CPFC3 < matlab.apps.AppBase

    % Properties that correspond to app components
    properties (Access = public)
        UIFigure                    matlab.ui.Figure
        CheckForSBDsButton          matlab.ui.control.Button
        TabGroup                    matlab.ui.container.TabGroup
        OverviewTab                 matlab.ui.container.Tab
        UIAxes                      matlab.ui.control.UIAxes
        UIAxes2                     matlab.ui.control.UIAxes
        UIAxes3                     matlab.ui.control.UIAxes
        SetupTab                    matlab.ui.container.Tab
        SetSBDFolderButton          matlab.ui.control.Button
        SBDFolderTextAreaLabel      matlab.ui.control.Label
        SBDFolderTextArea           matlab.ui.control.TextArea
        EarliestSBDDatePickerLabel  matlab.ui.control.Label
        EarliestSBDDatePicker       matlab.ui.control.DatePicker
        SBDListTab                  matlab.ui.container.Tab
        SavedSBDsTextAreaLabel      matlab.ui.control.Label
        SavedSBDsTextArea           matlab.ui.control.TextArea
        ExitButton                  matlab.ui.control.Button
        StateEditFieldLabel         matlab.ui.control.Label
        StateEditField              matlab.ui.control.EditField
    end

    properties (Access = public)
        %defaultSBDFolder = '\\atlas.shore.mbari.org\projectlibrary\CPF\Operations'; % Description
        defaultSBDFolder = 'C:\Users\gene\Documents\CPF\Operations'; % Description
        currentSBDFolder;
        earliestSBDDate;
    end

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

        % Code that executes after component creation
        function startupFcn(app)
            app.StateEditField.Value = 'Running startup code';
            app.TabGroup.SelectedTab = app.SetupTab;
            
            app.earliestSBDDate = datetime('now') - days(10);
            app.EarliestSBDDatePicker.Value = datetime(app.earliestSBDDate, "Format", "yyyyMMMdd HH:mm");
            
            app.SBDFolderTextArea.Value = app.defaultSBDFolder
            app.StateEditField.Value = 'Waiting for event';            
        end

        % Button pushed function: SetSBDFolderButton
        function SetSBDFolderButtonPushed(app, event)
            folderPath = uigetdir(app.defaultSBDFolder);
            app.SBDFolderTextArea.Value = folderPath;
        end

        % Button pushed function: ExitButton
        function ExitButtonPushed(app, event)
            app.delete
        end

        % Button pushed function: CheckForSBDsButton
        function CheckForSBDsButtonPushed(app, event)
            app.StateEditField.Value = 'Checking for SBDs';
            
            outlook = actxserver('Outlook.Application');
            mapi=outlook.GetNamespace('mapi');
            INBOX=mapi.GetDefaultFolder(6);
            emailIndex = INBOX.Items.Count;
            
            attList = '';
            attNum = 1;
            
            while (emailIndex > 0)
                app.StateEditField.Value = ['Checking for SBDs' num2str(emailIndex)];
                currentEmail=INBOX.Items.Item(emailIndex-1); %imports the most recent email
                subject = currentEmail.get('Subject');
                body = currentEmail.get('Body');
                senderName = currentEmail.get('SenderName');
                creationTime = currentEmail.get('CreationTime');
                dt = datetime(creationTime, 'InputFormat', 'MM/dd/uuuu hh:mm:ss aa');
                datetimeString = datestr(dt,'yyyymmmdd_HHMMSS');
                
                if(contains(subject, "[cpf-iridium-sbd]"))
                    fprintf(1, 'Email num: %d\tCreation Time: %s\tSender: %s\tSubject: %s\n', i+1, creationTime, senderName, subject);
                    
                    %% Saving attachments to current directory
                    attachments = currentEmail.get('Attachments');
                    if attachments.Count >=1
                        attName = attachments.Item(1).Filename;
                        dt = datetime(creationTime)
                        datetimeString = datestr(dt,'yyyymmmdd_HHMMSS')
                        attName = [attName '.' datetimeString];
                        
                        fullPath = [char(app.SBDFolderTextArea.Value) '\' attName];
                        if(~isfile(fullPath))
                            attachments.Item(1).SaveAsFile(fullPath)
                            fprintf('Saving Attachment: %s\n', fullPath);
                        else
                            fprintf('Attachment already in folder: %s\n', fullPath)
                        end
                        attList = [attList num2str(attNum) ' ' datetimeString ' ' attName newline]
                        app.SavedSBDsTextArea.Value = attList;
                        attNum = attNum + 1;
                    end
                end
                if dt < app.EarliestSBDDatePicker.Value
                    disp('Reached earliest SBD date\n')
                    break;
                end
                emailIndex = emailIndex - 1;
            end
            
            procesSBDs(char(app.SBDFolderTextArea.Value));
        end

        % Value changed function: EarliestSBDDatePicker
        function EarliestSBDDatePickerValueChanged(app, event)
            app.StateEditField.Value = "Changing Earliest SBD start date"
        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 848 682];
            app.UIFigure.Name = 'MATLAB App';

            % Create CheckForSBDsButton
            app.CheckForSBDsButton = uibutton(app.UIFigure, 'push');
            app.CheckForSBDsButton.ButtonPushedFcn = createCallbackFcn(app, @CheckForSBDsButtonPushed, true);
            app.CheckForSBDsButton.Position = [34 17 108 29];
            app.CheckForSBDsButton.Text = 'Check For SBDs';

            % Create TabGroup
            app.TabGroup = uitabgroup(app.UIFigure);
            app.TabGroup.Position = [34 65 802 541];

            % Create OverviewTab
            app.OverviewTab = uitab(app.TabGroup);
            app.OverviewTab.Title = 'Overview';

            % Create UIAxes
            app.UIAxes = uiaxes(app.OverviewTab);
            title(app.UIAxes, 'Battery Voltage')
            xlabel(app.UIAxes, 'X')
            ylabel(app.UIAxes, 'Y')
            zlabel(app.UIAxes, 'Z')
            app.UIAxes.Position = [288 342 468 151];

            % Create UIAxes2
            app.UIAxes2 = uiaxes(app.OverviewTab);
            title(app.UIAxes2, 'Pressure')
            xlabel(app.UIAxes2, 'X')
            ylabel(app.UIAxes2, 'Y')
            zlabel(app.UIAxes2, 'Z')
            app.UIAxes2.Position = [330 206 427 107];

            % Create UIAxes3
            app.UIAxes3 = uiaxes(app.OverviewTab);
            title(app.UIAxes3, 'Humidity')
            xlabel(app.UIAxes3, 'X')
            ylabel(app.UIAxes3, 'Y')
            zlabel(app.UIAxes3, 'Z')
            app.UIAxes3.Position = [315 25 457 132];

            % Create SetupTab
            app.SetupTab = uitab(app.TabGroup);
            app.SetupTab.Title = 'Setup';

            % Create SetSBDFolderButton
            app.SetSBDFolderButton = uibutton(app.SetupTab, 'push');
            app.SetSBDFolderButton.ButtonPushedFcn = createCallbackFcn(app, @SetSBDFolderButtonPushed, true);
            app.SetSBDFolderButton.Position = [5 439 120 33];
            app.SetSBDFolderButton.Text = 'Set SBD Folder';

            % Create SBDFolderTextAreaLabel
            app.SBDFolderTextAreaLabel = uilabel(app.SetupTab);
            app.SBDFolderTextAreaLabel.HorizontalAlignment = 'right';
            app.SBDFolderTextAreaLabel.Position = [57 471 68 22];
            app.SBDFolderTextAreaLabel.Text = 'SBD Folder';

            % Create SBDFolderTextArea
            app.SBDFolderTextArea = uitextarea(app.SetupTab);
            app.SBDFolderTextArea.Position = [140 439 339 56];

            % Create EarliestSBDDatePickerLabel
            app.EarliestSBDDatePickerLabel = uilabel(app.SetupTab);
            app.EarliestSBDDatePickerLabel.HorizontalAlignment = 'right';
            app.EarliestSBDDatePickerLabel.Position = [32 382 77 22];
            app.EarliestSBDDatePickerLabel.Text = 'Earliest SBD ';

            % Create EarliestSBDDatePicker
            app.EarliestSBDDatePicker = uidatepicker(app.SetupTab);
            app.EarliestSBDDatePicker.DisplayFormat = 'uuuuMMMdd';
            app.EarliestSBDDatePicker.ValueChangedFcn = createCallbackFcn(app, @EarliestSBDDatePickerValueChanged, true);
            app.EarliestSBDDatePicker.Position = [124 371 113 33];

            % Create SBDListTab
            app.SBDListTab = uitab(app.TabGroup);
            app.SBDListTab.Title = 'SBD List';

            % Create SavedSBDsTextAreaLabel
            app.SavedSBDsTextAreaLabel = uilabel(app.SBDListTab);
            app.SavedSBDsTextAreaLabel.HorizontalAlignment = 'right';
            app.SavedSBDsTextAreaLabel.Position = [58 473 74 22];
            app.SavedSBDsTextAreaLabel.Text = 'Saved SBDs';

            % Create SavedSBDsTextArea
            app.SavedSBDsTextArea = uitextarea(app.SBDListTab);
            app.SavedSBDsTextArea.Position = [58 206 686 266];

            % Create ExitButton
            app.ExitButton = uibutton(app.UIFigure, 'push');
            app.ExitButton.ButtonPushedFcn = createCallbackFcn(app, @ExitButtonPushed, true);
            app.ExitButton.Position = [545 22 97 29];
            app.ExitButton.Text = 'Exit';

            % Create StateEditFieldLabel
            app.StateEditFieldLabel = uilabel(app.UIFigure);
            app.StateEditFieldLabel.HorizontalAlignment = 'right';
            app.StateEditFieldLabel.Position = [191 24 55 22];
            app.StateEditFieldLabel.Text = 'State';

            % Create StateEditField
            app.StateEditField = uieditfield(app.UIFigure, 'text');
            app.StateEditField.Position = [261 22 201 26];

            % 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 = CPFC3

            % 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