function figH = newbladedsignalchk( filenames, signalSelection, filepath, handles )
% newbladedsignalchk
%   figH = newbladedsignalchk( filenames, signalSelection, filepath, handles )
%   creates a GUI for selection of the signals to the pass for display

%   Project: IMPACT
%   Title of Code: newbladedsignalchk
%   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.



%% change the filepath if necessary
cd1 = cd;
if nargin > 2
    if isempty(filepath)
        symbol = '';
        filepathTemp = fileparts(filenames{1});
    else
        symbol = filesep;
        filepathTemp = filepath;
    end
    cd( filepathTemp );
end

%% check if the 'Calculation' are 10 for filenames
%% & get the *.%* data files for *.PJ Bladed files
% filesnames are *.PJ files
% allBladedF{m} is *.%00 files
% lengthF is the length of allBladedF{m}
nFiles = length(filenames);
fullFiles = cell(1, nFiles);
lengthF = zeros(1, nFiles);
% notPowProd = [];
isPowProd = zeros(1, nFiles);

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

for m = 1:nFiles
    fullFiles{m} = [filepath, symbol, filenames{m}];
    All = bladedPrjRead(fullFiles{m});
    if isempty(All)
        cd(cd1);
        return
    end
    calType = All.calculation;
    % 10 -- power production, 11 -- normal stop, 12 -- emergency stop,
    % 14 -- idling, 15 -- parked
    %     if ~(calType==10||calType==11||calType==12||calType==14||calType==15)

    % CC0001: calculation type should be between 10 and 15
    if isempty(calType) || ~any(calType == 10:15)
        % CC0001
        
        if ~strcmp(guidata(handle_tempFig), 'yes2all')

            hWarn = wrndlgMLS(handle_tempFig, sprintf('The file %s is of incorrect type for post processing. It will be ignored. Continue?', filenames{m}));
            uiwait(hWarn);

            button = guidata(handle_tempFig);
            if strcmp(button, 'Cancel')
                close(handle_tempFig);
                cd(cd1);
                return
            end
        end
    else
        isPowProd(m) = 1;
        
        allBladedF1 = dir( [ fullFiles{m}, '.%*' ] );
        %% excluding files such as *.%AE
        tempAllName = {allBladedF1.name};
        tempInd = regexp(tempAllName, '\%[0-9]');
        allBladedF1(cellfun('isempty', tempInd)) = [];
        lengthF(m) = length(allBladedF1);
    end
end

% close the invisible figure
close(handle_tempFig);

% delete all non-power production files
isPowProd = logical(isPowProd);
fullFiles = fullFiles(isPowProd);
lengthF = lengthF(isPowProd);

warnMsg = 'Selected files do not have the same number of data group. The common data groups will be used.';
if isempty(lengthF) || min(lengthF) == 0
    zeroInd = (lengthF==0);
    if all(zeroInd)
        errordlgMLS('There is no appropriate data group for selected Bladed files.');
        cd(cd1);
        return
    else
        warnMsg = 'Some files do not have data group. These files will be removed and the common data groups will be used.';
        fullFiles(zeroInd) = [];
        lengthF(zeroInd) =[];
    end
end
        
[minLength, minL_ind] = min(lengthF);
if any(diff(lengthF))
    warndlgMLS(warnMsg);
    uiwait;
end


used_fullfile = fullFiles{minL_ind};
groupFiles = dir( [ used_fullfile, '.%*' ] );
% excluding files such as *.%AE
tempAllName = {groupFiles.name};
tempInd = regexp(tempAllName, '\%[0-9]');
groupFiles(cellfun('isempty', tempInd)) = [];
% Total number of variable group in the sensor file
nGroup = length( groupFiles );
used_filepath = fileparts(used_fullfile);

%% build the initial texts and listboxes
uiColor = get(0,'defaultUicontrolBackgroundColor');

figH = figureMLS( 'units', 'normalized', 'Position',[0.1 0.1 0.9 0.9], 'NumberTitle', 'Off',...
    'MenuBar','none','Name','Signal Selections', 'color', uiColor, 'WindowStyle', 'modal'); % open a new figure

movegui(gcf, 'center');

uicontrol('Style','pushbutton','units', 'normalized',...
    'Position',[0.64,0.0125,0.07,0.035],'String','OK',...
    'Callback',{@pushbutton_cont_Callback}, 'FontName', 'Verdana');

uicontrol('Style','pushbutton','units', 'normalized',...
    'Position',[0.74,0.0125,0.07,0.035],'String','Cancel',...
    'Callback',{@pushbutton_cancel_Callback}, 'FontName', 'Verdana');

handles.togglebutton_selectAll = uicontrol('Style','togglebutton','units', 'normalized',...
    'Position',[0.46,0.84,0.07,0.035],'String','Select All', 'Value', 0,...
    'Callback',{@pushbutton_selectAll_Callback}, 'FontName', 'Verdana');

uicontrol('Style','text','units', 'normalized', 'HorizontalAlignment','left',...
    'Position',[0.03,0.84,0.15,0.025],'String','Variable Group',...
    'Callback',{@text_VarGroup_Callback}, 'FontName', 'Verdana', 'FontWeight', 'bold');

uicontrol('Style','text','units', 'normalized', 'HorizontalAlignment','left',...
    'Position',[0.21,0.84,0.15,0.025],'String','Direction',...
    'Callback',{@text_radius_Callback}, 'FontName', 'Verdana', 'FontWeight', 'bold');

uicontrol('Style','text','units', 'normalized','HorizontalAlignment','left',...
    'Position',[0.31,0.84,0.15,0.025],'String','Signal list',...
    'Callback',{@text_signal_Callback}, 'FontName', 'Verdana', 'FontWeight', 'bold');

handles.listbox_VarGroup = uicontrol('Style','listbox', ...
    'tag', 'listbox_VarGroup','units', 'normalized',...
    'Position',[0.03,0.5,0.15,0.34],'backGroundColor', 'white' ,...
    'Callback',{@listbox_VarGroup_Callback}, 'FontName', 'Verdana');

handles.hListbox_radius = uicontrol('Style','listbox', 'tag',...
    'listbox_radius','units', 'normalized',...
    'Position',[0.21,0.64,0.07,0.2],'Max',2,'backGroundColor', 'white' ,...
    'Callback',{@listbox_radius_Callback}, 'FontName', 'Verdana');
          

% fullSig = signalConver('signal_list_config2.txt');
fullSig = translateBladedSig;
abbrevi = fullSig.abbreviation;
descrip = fullSig.description;
unitSig = fullSig.unit;

if isnumeric(fullSig) && (fullSig == -1)
    errordlgMLS('Signal description file was not found.');
    cd(cd1);
    return
end

%% get all data and build all the checkboxes

VarGroup = cell(1, nGroup);
sigRadius = cell(1, nGroup);
nRadius = zeros(1, nGroup);
ptFiles = cell(1, nGroup);
nGroupSignals = zeros(1, nGroup);
for iGroup = 1: nGroup
    
    currentPtFile = fullfile(used_filepath, groupFiles(iGroup).name);
    ptFiles(iGroup) = regexp(groupFiles(iGroup).name, '\%.*', 'match');
    All = bladedPtRead(currentPtFile);
    
    % in case error occurred during the reading
    if isempty(All)
        close(figH);
        cd(cd1);
        return
    end
    
    % the group name
    VarGroup{iGroup} = All.genlab;
    
    % the axival and its length
    if All.ndimens == 2
       sigRadius{iGroup} = {};
       nRadius(iGroup) = 0;
    else
        nRadius(iGroup) = All.dimens(2);
        if iscell(All.axival) % tidal bladed
            for p = 1:nRadius(iGroup)
                sigRadius{iGroup}{p} = All.axival{p};
            end
        else
            for p = 1:nRadius(iGroup)
                sigRadius{iGroup}{p} = num2str(All.axival(p));
            end
        end
    end
    
    % the unit
    unit = All.varunit;
    
    % the signal
    signal = All.variab;
    signalFull = All.variabFull;
    
    %     % *.%* variable group file

    % $$$   /* Total number of signal list for the corresponding variable group */
    nGroupSignals(iGroup) = length( signal );

    % initial coordinates
    x = 0.31;
    y = 0.82;

    % build checkboxes for one group
    for iGroupSignal = 1: nGroupSignals(iGroup)
        abb_ind = find(strcmp(abbrevi, signal{iGroupSignal}));
        if isempty(abb_ind) % not found the translations
           str = signalFull{iGroupSignal}(2:end-1);
           unitStr = bladedUnitConv(unit{iGroupSignal});
        else
           str =  descrip{abb_ind(1)};
           unitStr = unitSig{abb_ind(1)};
        end

        strFull = [str, ' [', unitStr, ']'];
       
        handles.checkbox( iGroup, iGroupSignal ) = ...
            uicontrol( 'Style', 'checkbox', 'units', 'normalized',...
            'Position', [ x, y, 0.6, 0.02 ],...
            'String', strFull, 'ToolTipString', strFull,...
            'Callback',{ @chk_boxes_Callback }, 'FontName', 'Verdana');

        x = fix( iGroupSignal / 25 ) * 0.1 + 0.31;
        y = 0.82 - 0.03 * rem( iGroupSignal, 25 );
    end

%     handles.radiusSelction(iGroup, :) = [1, zeros(1, nRadius-1)];

end

cd(cd1)

% is power production
handles.isPowProd = isPowProd;

% all percentage files
handles.ptFiles = ptFiles;

% radius selections
handles.radiusSelction = [ones(nGroup, 1), zeros( nGroup, max(nRadius)-1)];

% checkbox selections
handles.chkboxSelction = zeros( nGroup, max(nGroupSignals) );

% make the handles from newfgui2 to the present one
% put the check box handles into it as well
guidata( gcf, handles );

% set the group value to 1
% set up the string for it
% set the radius as the UserData

set(handles.listbox_VarGroup,... 
'Value',     1,...
'String',    VarGroup,...
'UserData',  sigRadius);

listbox_VarGroup_Callback(handles.listbox_VarGroup);
handles = setSignalSelection(handles, signalSelection);
guidata( gcf, handles );


function listbox_VarGroup_Callback(source,eventdata)
handles = guidata( source );
radiusSelection = handles.radiusSelction;

groupNo = get( source, 'Value' );
checkboxes = handles.checkbox;

% current group radius
currentRadius = radiusSelection( groupNo, : );
currentRadiusSelection = find( currentRadius );

% set current group checkboxes visible
for iCont =1: numel(checkboxes)
    if isfield(get(checkboxes(iCont)),'Visible')
        set( checkboxes(iCont), 'Visible', 'off' );
    end
end
for iCont=1: numel( checkboxes( groupNo, : ))
    if isfield(get(checkboxes(groupNo,iCont)),'Visible')
    set( checkboxes( groupNo, iCont ),'Visible','on');
    end
end
% extract the radius from the UserData
userData = get( source, 'UserData' );
radius = userData{ groupNo };

hListbox_radius =  handles.hListbox_radius;

set( hListbox_radius, 'String', radius, 'Value', currentRadiusSelection);

%% set the togglebutton for 'Select All'
chkbox = findobj(gcf, 'style', 'checkbox', 'visible', 'on');
selectVal = 1;
selectStr = 'Cancel All';
for m = 1: length(chkbox)
    if get(chkbox(m), 'Value') == 0
        selectVal = 0;
        selectStr = 'Select All';
        break
    end
end

set(handles.togglebutton_selectAll, 'Value', selectVal, 'String', selectStr);




function listbox_radius_Callback(source,eventdata)
handles = guidata( source );
radiusSelection = handles.radiusSelction;
% groupNo & radiusNo
groupNo = get( handles.listbox_VarGroup, 'Value' );
radiusNo = get( source, 'Value' );
% set selected radius values to 1
radiusSelection( groupNo, : ) = 0;
radiusSelection( groupNo, radiusNo) = 1;
% update guidata
handles.radiusSelction = radiusSelection;
guidata( source, handles );



function chk_boxes_Callback(source,eventdata)
handles = guidata( source );
chkboxSelection = handles.chkboxSelction;
value = get( source, 'Value' );

% get the groupNo & signalNo
hChkbox =  handles.checkbox;
[ groupNo, signalNo ] = find( hChkbox == source );

% set the chkbox seletion value to 0 or 1
chkboxSelection( groupNo, signalNo ) = value;
handles.chkboxSelction = chkboxSelection;
guidata( source, handles );






function pushbutton_cont_Callback(source,eventdata)

handles = guidata( source );

% signals.radius = handles.radiusSelction;
hRadius = handles.radiusSelction;
% signals.chkbox = handles.chkboxSelction;
hChkbox = handles.chkboxSelction;

% number of group
nGroup = size( hRadius, 1 );
userData = get( handles.listbox_VarGroup, 'UserData' );
% the variable to show selected group and radius for corresponding
% checkboxes
% the fieldname can be known from the signal listbox


m = 1;
groupChkRad = [];
for iGroup = 1: nGroup
    chkbox = find( hChkbox( iGroup, : ) );
    radiusInd = find( hRadius(iGroup, : ) );

    if ~isempty( chkbox )&&~isempty( radiusInd )
        iRadiusGroup = userData{iGroup};
        for p = 1: length( chkbox )
            % get the signal abbreviation name, excluding the unit
            % chkbox(p) is the number for checkbox
            signalNUnit = get( handles.checkbox( iGroup, chkbox(p) ), 'String' );
            signalName = regexprep( signalNUnit, '\s\[.*\]','' );
            for q = 1: length( radiusInd )
                signals.description{m} = signalName;
                unit = regexp( signalNUnit, '\[.*\]', 'match' ); % change the signal units into a formatted one
                signals.units(m) = unit; % units

                if isempty(iRadiusGroup)
                    radius = [];
                    signals.fullSig{m} = [signalName, ' ', unit{:}];
                else
                    radius = iRadiusGroup{ radiusInd(q) };
                    signals.fullSig{m} = [signalName, ' [', radius, '] ', unit{:}];
                end



                % groupChkRad is the number for group, chkbox and radius
                % for example, [ 2 3 1 ] means group 2, checkbox 3, radius 1
                groupChkRad( m, : ) = [ iGroup, chkbox(p), radiusInd(q) ];
                m = m + 1;
            end % q
        end % p
    end % 
end % iGroup


if isempty(groupChkRad)
    errordlgMLS('No signal is selected.');
    return;
else
    signals.groupChkRad = groupChkRad;
    signals.ptFiles = handles.ptFiles;
    signals.isPowProd = handles.isPowProd;
    signals.signalAbb = {}; % For compatibility with FAST 27/08/2012 CG
end
    
% cd( handles.mainpath );
close;

handles.returnFcnH(signals);


function pushbutton_cancel_Callback(source,eventdata)
close;

function pushbutton_selectAll_Callback(source, eventdat)

handles = guidata( source );
groupNo = get( handles.listbox_VarGroup, 'Value' );
chkbox = findobj(gcf, 'style', 'checkbox', 'visible', 'on');
value = get( source, 'Value' );
set(chkbox, 'Value', value); % set all chkboxes
if value == 1 % button is pressed
   set( source, 'String', 'Cancel All'); % set the string
elseif value == 0 % button is off
    set( source, 'String', 'Select All'); % set the string
end

handles.chkboxSelction(groupNo, 1:length(chkbox)) = value; 
guidata(source, handles);

