function varargout = addRemoveSims(varargin)
% addRemoveSims Add/Removes simulations from data analyser

%   Project: IMPACT
%   Title of Code: addRemoveSims
%   Relevant additional documentation:
%   Developer: Carlos Gonzalez
%   External Dependencies: NA
%
%   Disclaimer
%   CAUTION: It is strongly recommended that changes to this code
%   should be avoided without first consulting with authors.

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @addRemoveSims_OpeningFcn, ...
                   'gui_OutputFcn',  @addRemoveSims_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 addRemoveSims is made visible.
function addRemoveSims_OpeningFcn(hObject, eventdata, handles, varargin)
addIMPACTIcon(hObject);


% input
handlesFig = varargin{1};
handles.fcnH = varargin{2};

% group list
str = get(handlesFig.listbox_groupList, 'String');
set(handles.listbox_groupList, 'String', str);
group = get(handlesFig.listbox_groupList, 'Value');
set(handles.listbox_groupList, 'Value', group);

% file list
str = get(handlesFig.listbox_fileList, 'String');
set(handles.listbox_fileList, 'String', str);

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

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes addRemoveSims wait for user response (see UIRESUME)
% uiwait(handles.addRemoveSims);
movegui(hObject, 'center');
set(gcf, 'WindowStyle', 'modal');


% --- Outputs from this function are returned to the command line.
function varargout = addRemoveSims_OutputFcn(hObject, eventdata, handles) 



% --- Executes on selection change in listbox_groupList.
function listbox_groupList_Callback(hObject, eventdata, handles)

group = get(hObject, 'Value');
files = handles.handlesFig.files{group};
set(handles.listbox_fileList, 'String', files, 'Value', 1);


% --- Executes during object creation, after setting all properties.
function listbox_groupList_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in listbox_fileList.
function listbox_fileList_Callback(hObject, eventdata, handles)

% --- Executes during object creation, after setting all properties.
function listbox_fileList_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbutton_remove.
function pushbutton_remove_Callback(hObject, eventdata, handles)

str = get(handles.listbox_fileList, 'String');
val = get(handles.listbox_fileList, 'Value');
str(val) = [];
if isempty(str)
   errordlgMLS('Cannot remove all simulations.');
   return;
end
set(handles.listbox_fileList, 'String', str, 'Value', 1);

% update
group = get(handles.listbox_groupList, 'Value');
handles.handlesFig.fullFiles{group}(val) = [];
handles.handlesFig.files{group}(val) = [];
guidata(hObject, handles);


% --- Executes on button press in pushbutton_add.
function pushbutton_add_Callback(hObject, eventdata, handles)

handlesFig = handles.handlesFig;
group = get(handles.listbox_groupList, 'Value');

%% get filenames and filepath
pathsSelected = selectFiles(1, handlesFig.storedPaths);
if isempty(pathsSelected)
    return;
end

fullFiles = {};
hWait = waitbarMLS(1, 'Loading folders...');
set(hWait, 'pointer', 'watch');
for m = 1:numel(pathsSelected)
    dirName = pathsSelected{m};
    if isdir(dirName)
        allPath = getAllSubs(dirName);

        %% check if there are available files
        All = getSubfolder(allPath);
        fullFiles = [fullFiles; All.fullFiles];
    else
        fullFiles = [fullFiles; dirName];
    end
end
close(hWait);


if isempty(fullFiles)
    warndlgMLS('There are no available simulations in the selected folder and its subfolders.');
    return
end


handle_tempFig = figureMLS('visible', 'off', 'handleVisibility', 'off');
guidata(handle_tempFig, 'Cancel');

nFiles = length(fullFiles);
filenames = cell(nFiles, 1);
fileType = handles.handlesFig.loadFileType{group};

prevExt = '.$pj';
for m = 1:nFiles
    [path, name, ext] = fileparts(fullFiles{m});

    if ~strcmpi(prevExt, ext)
        if ~strcmp(guidata(handle_tempFig), 'yes2all')
            hWarn = wrndlgMLS(handle_tempFig, sprintf('The file %s is a different file type from previous one. It will be ignored. Continue?', fullFiles{m}));
            uiwait(hWarn);
            button = guidata(handle_tempFig);
            if strcmp(button, 'Cancel')
                close(handle_tempFig);
                return
            end
            fullFiles{m} = [];
        else
            fullFiles{m} = [];
        end
    end
    filenames{m} = [name, ext];
end
close(handle_tempFig);

fullInd = cellfun('isempty', fullFiles);
fullFiles = fullFiles(~fullInd);
filenames = filenames(~fullInd);

handlesFig.storedPaths = pathsSelected;

% change $pj into $PJ
filenames = changePJ(filenames);

% tell which kind of files have been loaded, flex or bladed
if strcmpi(ext(2:end), '$PJ' )

    [fullFiles, fileInd] = sort(fullFiles);
    filenames = filenames(fileInd);

    %% set file names
    filenames = regexprep(filenames, '\.\$PJ', '');% discard .$PJ
    fullFiles = regexprep(fullFiles, '\.\$PJ', '');% discard .$PJ

else
    filenames = [];
    
end
[uniqueFullFiles uniqueVals] = unique([handlesFig.fullFiles{group}; fullFiles],'first');
noFullFiles = numel([handlesFig.fullFiles{group}; fullFiles]);
if numel(uniqueVals)~=noFullFiles
    fileNamesTemp = [handlesFig.files{group}; filenames];
    handlesFig.files{group} = fileNamesTemp(uniqueVals);
    handlesFig.fullFiles{group} = uniqueFullFiles;
    warndlgMLS('Repeated simulations will not be loaded','Warning');
else
    handlesFig.files{group} = [handlesFig.files{group}; filenames];
    handlesFig.fullFiles{group} = [handlesFig.fullFiles{group}; fullFiles];
end

% update guidata
handles.handlesFig = handlesFig;
guidata(hObject, handles);
listbox_groupList_Callback(handles.listbox_groupList, [], handles)


function bladedReturn(signals)
% build the signal list and update guidata

hFigure = findobj( 'tag', 'addRemoveSims' ); % handles to the main figure
handles = guidata( hFigure );
handlesFig = handles.handlesFig;

group = get(handles.listbox_groupList, 'Value');

%% update signal list
handlesFig.signal{group} = signals.fullSig; % signal list
handlesFig.units{group} = signals.units; % group units
handlesFig.signalBladed(group) = signals;

% exclude non-power production files
handlesFig.files{group} = [handlesFig.files{group}; handlesFig.files{group}(signals.isPowProd)];
handlesFig.fullFiles{group} = [handlesFig.fullFiles{group}; handlesFig.fullFiles{group}(signals.isPowProd)];

handles.handlesFig = handlesFig;
guidata( hFigure, handles );

listbox_groupList_Callback(handles.listbox_groupList, [], handles)


% --- Executes on button press in pushbutton_ok.
function pushbutton_ok_Callback(hObject, eventdata, handles)
fig = gcf;
hFig = findobj('tag', 'newfgui2');
guidata(hFig, handles.handlesFig);

set(fig, 'WindowStyle', 'normal');
handles.fcnH.groupList(handles.handlesFig.listbox_groupList, [], handles.handlesFig);
close(fig);

% --- Executes on button press in pushbutton_cancel.
function pushbutton_cancel_Callback(hObject, eventdata, handles)
close;


