classdef SetupComplete < matlab.hwmgr.internal.hwsetup.TemplateBase
    %SetupComplete This is an TI C2000 specific implementation of a
    %Launch Examples screen. This screen will be displayed at the end of
    %the TI C2000 Setup to give the installer an option to open the examples
    %page for C2000 Microcontroller Blockset

    %   Copyright 2017-2024 The MathWorks, Inc.

    properties(Access = {?matlab.hwmgr.internal.hwsetup.TemplateBase,...
            ?hwsetuptest.util.TemplateBaseTester})
        % Description - Description for the screen (Label)
        Description
        %LaunchCheckbox - Checkbox to launch the support package examples
        LaunchCheckbox
    end

    methods
        function obj = SetupComplete(workflow)
            obj@matlab.hwmgr.internal.hwsetup.TemplateBase(workflow);
            try
                obj.generateRWResources(workflow.SelectedProcessors,workflow.CCSInstallLocation);
            catch ME
                %Ignore errors
            end
            if obj.TemplateLayout == matlab.hwmgr.internal.hwsetup.TemplateLayout.GRID
                widgetParent = obj.ContentGrid;
            else
                widgetParent = obj.ContentPanel;
            end
            obj.Description = matlab.hwmgr.internal.hwsetup.Label.getInstance(widgetParent);

            % Set Title
            obj.Title.Text = message('hwsetup:template:LaunchExamplesTitle').getString;

            % Set Description Properties
            obj.Description.Text = message('TIC2000:hwsetup:SetupCompleteDescription').getString;
            obj.Description.Color = matlab.hwmgr.internal.hwsetup.util.Color.WHITE;

            % Set HelpText properties containing default text(‘lorem ipsum’) to empty strings
            obj.HelpText.AboutSelection = '';
            obj.HelpText.WhatToConsider = '';

            hasExamples = isfolder(fullfile(docroot,'ti-c2000'));
            if hasExamples
                obj.LaunchCheckbox = matlab.hwmgr.internal.hwsetup.CheckBox.getInstance(widgetParent);

                % Set LaunchCheckbox Properties
                obj.LaunchCheckbox.Text = message('TIC2000:hwsetup:LaunchExamplesCheckboxText').getString;
                obj.LaunchCheckbox.Value = true;
            end

            % Set callback when finish button is pushed
            obj.NextButton.ButtonPushedFcn = @obj.launchExamplesAndCloseUI;

            if obj.TemplateLayout == matlab.hwmgr.internal.hwsetup.TemplateLayout.GRID
                % set up grid layout
                obj.ContentGrid.RowHeight = {'fit', 'fit'};
                obj.ContentGrid.ColumnWidth = {'1x'};

                % arrange widgets
                obj.Description.Row = 1;
                if ~isempty(obj.LaunchCheckbox)
                    obj.LaunchCheckbox.Row = 2;
                end
            else
                % set widget positions
                obj.Description.Position = [20 330 430 40];
                if ~isempty(obj.LaunchCheckbox)
                    obj.LaunchCheckbox.Position = [20 300 430 20];
                    obj.LaunchCheckbox.ValueChangedFcn = @obj.checkboxCallback;
                    obj.LaunchCheckbox.Value=obj.Workflow.ShowExamples;
                else
                    obj.Workflow.ShowExamples = false;
                end
            end
        end

        function out = getPreviousScreenID(~)
            out = 'codertarget.tic2000.hwsetup.ConfirmTPInstallation';
        end

        function launchExamplesAndCloseUI(obj, ~, ~)
            % LAUNCHEXAMPLESANDCLOSEUI - Callback when finish button is pushed that launches the
            % example page and call finish method to close HW Set up
            % window

            if ~isempty(obj.LaunchCheckbox) && obj.LaunchCheckbox.Value
                helpview(fullfile(docroot,'ti-c2000','c2b.map'),'c2b_doccenter-examplelandingpage');
            end
            matlab.hwmgr.internal.hwsetup.TemplateBase.finish([], [], obj);
        end
        % Generate necessary mat files required for Register Read/write
        % block
        function generateRWResources(~,selectedProcessors, ccsPath)
            targetFolder = codertarget.target.getTargetFolder('TI C2000');
            hardwareBoards = codertarget.target.getAllHardwareBoards('TI C2000');
            if isfolder(ccsPath)
                % Generate xml for ti registers
                prefSettings = getpref('MathWorksTIC2000Preferences');
                % Use preference to override the default path selection for
                % RW resources
                if isfield(prefSettings, 'overridePathForRWToolsInstall') && ~isempty(prefSettings.('overridePathForRWToolsInstall'))
                    c2bRegistersXMLFolder = fullfile(prefSettings.('overridePathForRWToolsInstall'), 'tic2000Registers');
                    c2bRegistersBitsInfoFolder = fullfile(prefSettings.('overridePathForRWToolsInstall'), 'tic2000BitsInfo');
                else
                    thirdPartyFolder = codertarget.target.getThirdPartyToolsRegistryFolder(targetFolder);
                    c2bRegistersXMLFolder = fullfile(fileparts(thirdPartyFolder),'tic2000Registers');
                    c2bRegistersBitsInfoFolder = fullfile(fileparts(thirdPartyFolder),'tic2000BitsInfo');
                end
                %Create Register XMLs for all the supported TIC2000 targets
                codertarget.tic2000.internal.createXMLforTIRegisters(c2bRegistersXMLFolder);

                %% Generate MAT files for bits info for the selected targets in set up screen

                % Get list of RW block device family options
                [subFamilyList, ~] = codertarget.tic2000.internal.getRWBlockOptions();
                
                for processorIdx = 1:length(selectedProcessors)
                    % Find the hw board corresponding to the selected
                    % processor
                    idx = find(contains({hardwareBoards(:).Name}, selectedProcessors{processorIdx}), 1);
                    hwBoard = hardwareBoards(idx);
                    subFamily = hwBoard.SubFamily;  
                    % For 28p65x, file name is with capital P
                    if strcmp(subFamily,'28p65x')
                        subFamily = '28P65x';
                    end
                    % Find the list of device names for the corresponding
                    % selected processor
                    RWDeviceList = subFamilyList(contains(subFamilyList(:),subFamily));                    
                    for idx = 1:length(RWDeviceList)
                        deviceName = strrep(RWDeviceList{idx},'_','');
                        c2bRegisterXMLFileName = fullfile(c2bRegistersXMLFolder, [deviceName, 'Registers.xml']);
                        c2bRegisterMATFileName = strrep(c2bRegisterXMLFileName,'.xml','.mat');
                        if isfile(c2bRegisterMATFileName)
                            regDef = load(c2bRegisterMATFileName,'regDef');
                            regDef =  regDef.regDef;
                            codertarget.tic2000.internal.generateBitsInfoMatFiles(regDef, c2bRegistersBitsInfoFolder, ccsPath);
                        end
                    end
                end
            end
        end %generateRWResources
    end

    methods(Access = 'private')
        function checkboxCallback(obj, src, ~)
            obj.Workflow.ShowExamples = src.Value;
        end
    end

end
