% WRITTEN BY CAGDAS

%%shows heart rate screen
function varargout = GUI_showHeartRateScreen(varargin)
% GUI_SHOWHEARTRATESCREEN MATLAB code for GUI_showHeartRateScreen.fig
%      GUI_SHOWHEARTRATESCREEN, by itself, creates a new GUI_SHOWHEARTRATESCREEN or raises the existing
%      singleton*.
%
%      H = GUI_SHOWHEARTRATESCREEN returns the handle to a new GUI_SHOWHEARTRATESCREEN or the handle to
%      the existing singleton*.
%
%      GUI_SHOWHEARTRATESCREEN('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in GUI_SHOWHEARTRATESCREEN.M with the given input arguments.
%
%      GUI_SHOWHEARTRATESCREEN('Property','Value',...) creates a new GUI_SHOWHEARTRATESCREEN or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before GUI_showHeartRateScreen_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to GUI_showHeartRateScreen_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help GUI_showHeartRateScreen

% Last Modified by GUIDE v2.5 06-Dec-2013 12:43:54

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @GUI_showHeartRateScreen_OpeningFcn, ...
                   'gui_OutputFcn',  @GUI_showHeartRateScreen_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before GUI_showHeartRateScreen is made visible.
function GUI_showHeartRateScreen_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to GUI_showHeartRateScreen (see VARARGIN)

% Choose default command line output for GUI_showHeartRateScreen
handles.ctrl = varargin{1};
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);
populateSessionList(handles);

% UIWAIT makes GUI_showHeartRateScreen wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = GUI_showHeartRateScreen_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;




% --- Executes on button press in btDownload.
function btDownload_Callback(hObject, eventdata, handles)
% hObject    handle to btDownload (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
mam = MotoActvManager(handles.ctrl);
msgbox('You will be notified after Download is complete. Please be patient');
if(handles.ctrl.downloadEnabled) mam.downloadData(); end
msgbox('Download completed, uploading to Database');

mam.exportToDB();
msgbox('uploaded.');
populateSessionList(handles);



% --- Executes on selection change in popSessionList.
function popSessionList_Callback(hObject, eventdata, handles)
% hObject    handle to popSessionList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ilist = get(hObject,'Value'); % the item number in the list
list = get(hObject,'String'); % the items in the list
user = handles.ctrl.getUser(); % get current user
data = DatabaseManager.getHeartRateData(list{ilist},user.id); % retrieve HR
d = cell2mat(data); % from cell to array

N=length(d);       % number of data
M=ceil(N/300);      % number of average
% Create 5 min blocks
for i=1:1:M-1 
   ave(i)=mean(d((i-1)*300+1:i*300));

end

ave(M)=mean(d((M-1)*300+1:N));
%plotting
plot(handles.axHR,1/60:5/60:5* length(ave)/60,ave,'r');
title('heart-rate average & time period plot');
xlabel('time [hour]');
ylabel('heart-rate average');
ylim([0 120]);
HR.rawData = d;
HR.session = list{ilist};
handles.ctrl.saveHeartRateData(HR);

%check for apnea
sleepApneaManager(d);
%% On the assumption that the data is in ready format%%






% Hints: contents = cellstr(get(hObject,'String')) returns popSessionList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popSessionList


% --- Executes during object creation, after setting all properties.
function popSessionList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popSessionList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over popSessionList.
function popSessionList_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to popSessionList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on key press with focus on popSessionList and none of its controls.
function popSessionList_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to popSessionList (see GCBO)
% eventdata  structure with the following fields (see UICONTROL)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in btSleepPattern to create sleep patterns.
function btSleepPattern_Callback(hObject, eventdata, handles)
% hObject    handle to btSleepPattern (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%load('Controller_currentHeartRate.mat')
data = handles.ctrl.getHeartRateData(); %get the heart rate data
p = SleepPatternManager.createSleepPatterns(data);
for(i=1:length(p.hypnogram))
    patterns.hypnogram(i) = num2str(p.hypnogram(i));

end
patterns.session = p.session;
user = handles.ctrl.getUser();
if(~DatabaseManager.doesSessionExistinPatterns(patterns.session,user.id))
    DatabaseManager.saveSleepPattern(patterns,user.id,'MotoActv');
end
patterns.hypnogram = str2num(patterns.hypnogram')';
handles.ctrl.saveSleepPatterns(patterns);
close all
GUI_showSleepPatternManager(handles.ctrl);

% --- Executes on button press in bt_back to go back.
function bt_back_Callback(hObject, eventdata, handles)
close all
GUI_showMainScreen(handles.ctrl)
% hObject    handle to bt_back (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


%populates sessions
function populateSessionList(handles)
user = handles.ctrl.getUser();
sessionList = DatabaseManager.getHRSessions(user.id);
set(handles.popSessionList,'String',sessionList);

