%{ 
    brightnessSignal.m
    Krystof Sara <xsarak00@stud.feec.vutbr.cz> 2019-2020

    Prumerovaci algoritmus, jenz prevadi videozaznam na PPG signal.
%}

function [ui] = brightnessSignal(vidfile, ui)

% Overeni existence souboru
if exist(vidfile, 'file') ~= 2
    error('Not a videofile.')
end

% Vypnuti tlacitek, by nedochazelo k naruseni zpracovani
push_off;

% Videoobject + nacteni metadat
vdata = VideoReader(vidfile);
dur = vdata.Duration;
ui.frate = vdata.FrameRate;
for_len = floor(ui.frate*dur);
ui.framez = zeros(1, ceil(for_len));

% Zpetna vazba operatorovi GUI
ui.wait = waitbar(0, 'Zpracovávám videozáznam...');
ui.processing_done = false;

for i = 1:for_len
    % Ochrana pred zavrenim waitbaru; pokud je okno nahle zavreno, dosud
    % zpracovane snimky jsou pouzity dale pro zpracovani signalu
    if ~isvalid(ui.wait)
        break;
    end
    
    % Ochrana na konci zaznamu
    if hasFrame(vdata)
        rawF = readFrame(vdata);
        frame = im2double(rawF);
        redChannel = frame(:,:,1);
        
        % Invertovani signalu
        ui.framez(i) = 1-mean(redChannel(:));
        waitbar(i/for_len, ui.wait);
    else
        break;
    end
end
ui.processing_done = true;
push_reset;

if isvalid(ui.wait)
    close(ui.wait);
end

%% Dodatkove funkce pro praci s tlacitky

    % Reaktivace tlacitek
    function push_reset
        set(ui.push_load, 'Enable', 'on');
        set(ui.push_tools, 'Enable', 'on');
        set(ui.push_history, 'Enable', ui.history_button_enable);
    end

    % Deaktivace vsech tlacitek
    function push_off
        set(ui.push_load, 'Enable', 'off');
        set(ui.push_tools, 'Enable', 'off');
        set(ui.push_save, 'Enable', 'off');
        set(ui.push_history, 'Enable', 'off');
    end

end