%WRITTEN BY CAGDAS

function varargout = GUI_showSleepPatternManager(varargin)
% GUI_SHOWSLEEPPATTERNMANAGER MATLAB code for GUI_showSleepPatternManager.fig
%      GUI_SHOWSLEEPPATTERNMANAGER, by itself, creates a new GUI_SHOWSLEEPPATTERNMANAGER or raises the existing
%      singleton*.
%
%      H = GUI_SHOWSLEEPPATTERNMANAGER returns the handle to a new GUI_SHOWSLEEPPATTERNMANAGER or the handle to
%      the existing singleton*.
%
%      GUI_SHOWSLEEPPATTERNMANAGER('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in GUI_SHOWSLEEPPATTERNMANAGER.M with the given input arguments.
%
%      GUI_SHOWSLEEPPATTERNMANAGER('Property','Value',...) creates a new GUI_SHOWSLEEPPATTERNMANAGER or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before GUI_showSleepPatternManager_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to GUI_showSleepPatternManager_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_showSleepPatternManager

% Last Modified by GUIDE v2.5 03-Dec-2013 12:13:56

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @GUI_showSleepPatternManager_OpeningFcn, ...
                   'gui_OutputFcn',  @GUI_showSleepPatternManager_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_showSleepPatternManager is made visible.
function GUI_showSleepPatternManager_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_showSleepPatternManager (see VARARGIN)

% Choose default command line output for GUI_showSleepPatternManager
handles.output = hObject;


handles.ctrl = varargin{1};
sessions = populateSessions(handles);
if(~isempty(sessions)) handles.sessions = sessions;end

populateCharts(handles,'MotoActv');
guidata(hObject, handles);
% UIWAIT makes GUI_showSleepPatternManager wait for user response (see UIRESUME)
% uiwait(handles.figure1);

function sessions = populateSessions(handles)
user = handles.ctrl.getUser();
data = DatabaseManager.getSleepSessions(user.id);
if(~strcmp(data{1,1},'No Data'))
for(i=1:size(data,1))
    
sessionList{i} = [data{i,1} ' - ' data{i,2}]; 
end
    set(handles.popSessions,'String',sessionList);
sessions = data;

else sessions = [];
end
% --- Outputs from this function are returned to the command line.
function varargout = GUI_showSleepPatternManager_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 btnDownloadZeo.
function btnDownloadZeo_Callback(hObject, eventdata, handles)
% hObject    handle to btnDownloadZeo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
MyZeoManager(handles.ctr.getUser());
handles.sessions = populateSessions(handles);
% --- Executes on button press in btnMain.
function btnMain_Callback(hObject, eventdata, handles)
% hObject    handle to btnMain (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
close all
GUI_showMainScreen(handles.ctrl);

% --- Executes on button press in btnSuggestions.
function btnSuggestions_Callback(hObject, eventdata, handles)
% hObject    handle to btnSuggestions (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
patterns = handles.ctrl.getSleepPatterns();
patternCell{1} = patterns.hypnogram;
sug.score = sleepQualityManager.getScore(patternCell);

sug.session = patterns.session;
user = handles.ctrl.getUser();
if(~DatabaseManager.doesSessionExistinSuggestions(sug.session,user.id))
    DatabaseManager.saveSuggestion(sug.session,user.id,sug.score) %saveSuggestion(Session,userId,score)
end
handles.ctrl.saveSuggestions(sug);
close all
GUI_showSuggestionScreen(handles.ctrl);
% --- Executes on selection change in popSessions.
function popSessions_Callback(hObject, eventdata, handles)
% hObject    handle to popSessions (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popSessions contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popSessions
user = handles.ctrl.getUser();

ilist = get(hObject,'Value');
choosenItem = handles.sessions(ilist,:);
pattern.session = choosenItem{1};
pattern.hypnogram = DatabaseManager.getSleepPattern(user.id,choosenItem{2},pattern.session);
handles.ctrl.saveSleepPatterns(pattern);
populateCharts(handles,choosenItem{2});

% --- Executes during object creation, after setting all properties.
function popSessions_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popSessions (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

function populateCharts(handles,type)
patterns = handles.ctrl.getSleepPatterns();

if(~isempty(patterns))
    %%if(strcmp(type,'MyZeo'))
    hypno=patterns.hypnogram;
    [a1,b1]=hist(hypno,unique(hypno));
    labels={'NAN','AWAKE','REM','LIGHT','DEEP'};
    pie(handles.axPie,a1,labels(b1+1));
    bar(handles.axPattern,patterns.hypnogram);
    set(handles.axPattern,'YTick',0:1:4);
    set(handles.axPattern,'YTickLabel',labels);
    set(handles.axPattern,'XTick',0:6:length(patterns.hypnogram));
    for i=0:6:length(patterns.hypnogram)
        labelsX{i/6+1} = num2str(0.5*i/6);
    end
    set(handles.axPattern,'XTickLabel',labelsX);
%     else
%         hypno=patterns.hypnogram;
%         new_hypno=hypno;
%         for i=1:length(hypno)
%             if (hypno(i)<1)
%             new_hypno(i)=1;
%         elseif (hypno(i)>=1&&hypno(i)<2)
%             new_hypno(i)=2;
%             elseif (hypno(i)>=2&&hypno(i)<3.5)
%             new_hypno(i)=3;
%             else
%             new_hypno(i)=4;
%             end
%         end
%         
%     [a1,b1]=hist(new_hypno,unique(new_hypno));
%     labels={'AWAKE','REM','LIGHT','DEEP'};
%     pie(handles.axPie,a1,labels(b1));
%     a = 1:size(patterns.hypnogram,2);
%     values = spcrv([[a(1) a a(end)];[patterns.hypnogram(1) patterns.hypnogram patterns.hypnogram(end)]],7);
% 
%     values(2,:)=values(2,:)./max(values(2,:))*4;
%     plot(handles.axPattern,values(1,:),values(2,:),'b','LineWidth',2);
% 
% 
%     %plot(handles.axPattern,patterns.hypnogram);
%     set(handles.axPattern,'YTick',0:1:4);
%     set(handles.axPattern,'YTickLabel',labels);
%     set(handles.axPattern,'XTick',0:6:length(patterns.hypnogram));
%     end
    % Update handles structure

end
