/*jslint node: true */
/*jslint browser: true*/
/*jslint nomen: true*/
/*global angular, BaseController, emailFrom, realPath*/
'use strict';

var scheduleController = BaseController.extend({

    /**
     * Initialize  Controller
     * @param {obj} $scope, current controller scope
     * @param $location
     * @param $routeParams
     * @param reportService
     * @param wizardSharedService
     * @param commonHelper
     * @param notificationService
     * @param modalWindowService
     * @param environmentService
     */

    init: function ($scope, $location, $routeParams, reportService, wizardSharedService, commonHelper, notificationService, modalWindowService) {
        var self = this;

        self.$scope = $scope;

        this.$location            = $location;
        this.$routeParams         = $routeParams;
        this._reportService       = reportService;
        this._wizardSharedService = wizardSharedService;
        this._commonHelper        = commonHelper;
        this._notificationService = notificationService;

        this._super($scope);

        this.$scope.modalWindow   = modalWindowService;

        $scope.emailFrom = emailFrom;
        $scope.realPath  = realPath;

        $scope.validation   = {};

        $scope.notification = {};
        $scope.SQL          = {};
        $scope.schedule     = {};
        $scope.schedules    = {}; // all schedules for this report

        self.$scope.alertData   = {};
        self.$scope.hostcontexts = {};
        self.$scope.excludedHosts = '';
        self.$scope.hostselectionstate = {};
        self.$scope.showEnvironmentFilterButtons = false;

        $scope.reportLabel  = {};
        $scope.reportCategory = {};
        $scope.reportId     = '';
        $scope.savedSearchName = {};
        $scope.savedSearchCategory = {};

        self.$scope.reportCategories = ReportCategories;

        $scope.is_public    = {};

        self.$scope.reportRoles = {};

        self.$scope.roles    = this._commonHelper.getRolesArray();
        self.$scope.is_admin = self._commonHelper.checkifAdmin(self.$scope.roles);

        $scope.loadedSchedule = false;
        $scope.save_allowed   = true;
        $scope.saveContext    = false;

        // when load schedule - save hostcontext
        $scope.savedHostcontextsprofileid = '';
        $scope.savedHostcontextspath      = {};
        $scope.savedHostcontexts          = {};



        self.$scope.Math = Math;
        self.$scope.Date = Date;
        $scope.hostList = {};
        $scope.originalHostList = {};



        if (!self._commonHelper._isObjEmpty(self._wizardSharedService.restoreScopeState())) {

            self.$scope.SQL = self._wizardSharedService.restoreScopeState();

            self.$scope.reportLabel.input     = self._commonHelper.restoreReportLabel();
            self.$scope.savedSearchName = self.$scope.reportLabel;

            self.$scope.reportCategory      = self._commonHelper.restoreReportCategory();
            self.$scope.savedSearchCategory.input = self.$scope.reportCategory;

            self.$scope.reportId    = self._commonHelper.restoreReportId();
            self.$scope.reportRoles = self._commonHelper.restoreReportRoles();

            if (self.$scope.reportId !== undefined && self.$scope.reportId !== '') {
                self._refreshScheduleList();
            }

            if (self.$scope.SQL === undefined || self.$scope.SQL.SQLSTRING === '') {
                var error = self._notificationService.createObjectForNotification('error', 500, 'Error getting report. Please return to the report list');
                self._notificationService.setNotification(error.type, error.data);
            }

            self._commonHelper.setContextVariables(self.$scope, self.$scope.SQL);
        }
        //load report
        else if ($routeParams.reportid !== undefined) {
                self._reportService.loadReport($routeParams.reportid).then(
                    function (result) {
                    var data = result.data;
                    var formData     = angular.fromJson(data['AdvancedReportsData']);
                    var scheduleData = angular.fromJson(data['scheduleData']);

                    self.$scope.SQL  = angular.fromJson(formData.SQL);

                    self.$scope.reportLabel.input = data.label;
                    self.$scope.savedSearchName   = self.$scope.reportLabel;
                    self.$scope.reportCategory = (data.reportCategory !== undefined ? data.reportCategory : '' );
                    self.$scope.savedSearchCategory.input = data.reportCategory;

                    self.$scope.reportId          = $routeParams.reportid;
                    self.$scope.loadedSearch      = true;
                    self.$scope.saveContext       = false;

                    $scope.reportRolesTMP    = (data.sharedPermission  !== undefined ? angular.fromJson(data.sharedPermission)  : {});
                    angular.forEach($scope.reportRolesTMP, function(key, value){
                       $scope.reportRoles[key] = true;
                    });


                    // we don't have to call _refreshScheduleList on load, because report already has information about all schedules
                    if (data.schedules !== undefined && data.schedules !== null && data.schedules.length>0)
                    {
                        // build array, where key => id and data - schedule item info
                        self._constructSchedulesList(data.schedules);
                    }

                },
                function(error) {
                    var error = self._notificationService.createObjectForNotification('error', 500, 'Error getting report. Please try to load report again');
                    self._notificationService.setNotification(error.type, error.data)
                });
        }

        self._initializeSheduleData();
    },

    defineScope: function() {
        this.$scope.instance = "scheduleController";

        this.$scope.saveSchedule         = this.saveSchedule.bind(this);
        this.$scope.deleteSchedule       = this.deleteSchedule.bind(this);
        this.$scope.editSchedule         = this.editSchedule.bind(this);
        this.$scope.viewSchedule         = this.viewSchedule.bind(this);
        this.$scope.cancelSchedule       = this.cancelSchedule.bind(this);
        this.$scope.convertGMTHumanReadableToLocalTime       = this.convertGMTHumanReadableToLocalTime.bind(this);;

        this.$scope.updateDayField       = this.updateDayField.bind(this); // connect to datepicker

        //helper fnc
        this.$scope.isObjEmpty          = this.checkIfObjEmpty.bind(this);

        //TODO: refactor
        this.$scope.roles_disablePublicReport = this.roles_disablePublicReport.bind(this);
        this.$scope.publicReport_disableRoles = this.publicReport_disableRoles.bind(this);

        this.$scope.validateForm = this.validateForm.bind(this);
    },
    defineListeners: function() {
        var self = this;

        self.$scope.$on("hostContextApply_Event", function(event, hostContextObj) {
            self.$scope.hostcontextsprofileid = angular.copy(hostContextObj.hostcontextsprofileid);
            self.$scope.hostcontextspath      = angular.copy(hostContextObj.hostcontextspath);
            self.$scope.hostcontexts          = angular.copy(hostContextObj.hostcontexts);
            self.$scope.alertData.hostContexts = angular.copy(hostContextObj.hostcontexts);
            // set report properties so report will be executed with new filter
            //self._wizardSharedService.reportPropertiesChanged(self._commonHelper.getReportData(self.$scope));
            self.$scope.showFilter = false;
        });

        self.$scope.$on('environmentExcludeChanged_Event', function(event, excludedHosts) {

            if (Object.keys(excludedHosts).length)
            {
                self.$scope.alertData.excludedHosts = {name: Object.values(excludedHosts).join(', '), excludes: Object.keys(excludedHosts)};
                self.$scope.SQL.excludedHosts = {name: Object.values(excludedHosts).join(', '), excludes: Object.keys(excludedHosts)};
                self.$scope.excludedHosts = {name: Object.values(excludedHosts).join(', '), excludes: Object.keys(excludedHosts)};
            }
            else {
                self.$scope.alertData.excludedHosts = '';
                self.$scope.excludedHosts = '';
                self.$scope.SQL.excludedHosts = '';
            }
        });


        self.$scope.$watchCollection('[schedule.minute, schedule.hour]', () => {
            const [startMinute, endMinute] = self.$scope.schedule.minute
                .replace('Min', '')
                .split('_')
                .map(v => parseInt(v));
            const hour = parseInt(self.$scope.schedule.hour.replace('GMT_Hr', ''));
            self.$scope.localTime = this.generateLocalTime(hour, startMinute, endMinute);
        });
    },

    generateLocalTime: function(hour, startMinute, endMinute) {
        const startLocalTime = moment.utc(`${hour}:${startMinute}`, 'HH:mm').utcOffset(-(new Date()).getTimezoneOffset()).format('HH:mm');
        // if end minute == 0 then on the UI was selected 60 and hour should be incremented
        //  e.g. 10:60 => 11:00
        if (endMinute == 0) {
            hour += 1;
        }
        const endLocalTime = moment.utc(`${hour}:${endMinute}`, 'HH:mm').utcOffset(-(new Date()).getTimezoneOffset()).format('HH:mm');
        return `${startLocalTime} - ${endLocalTime}`;
    },

    editSchedule: function(id)
    {
        var self = this;
        var $scope = self.$scope;

        if (self.$scope.schedules[id].scheduleData !== undefined)
        {
            self._setScheduleData(id);
            $scope.loadedSchedule = true;
            $scope.save_allowed = true;
            //unset save context checkbox
            $scope.saveContext  = false;
            setTimeout(processPageBeforeLeave, 1000)
        }
    },

    convertGMTHumanReadableToLocalTime: function(humanReadableGMT) {
        const gmtTimePart = humanReadableGMT.substr(-8);

        const [gmtHour, gmtMinutes] = gmtTimePart.split(':');
        const [gmtStartMinute, gmtEndMinute] = gmtMinutes.split('-').map(v => parseInt(v));
        const localTime  = this.generateLocalTime(parseInt(gmtHour), gmtStartMinute, gmtEndMinute);

        return localTime;
    },

    viewSchedule: function(id)
    {
        var self = this;
        var $scope = self.$scope;
        if (self.$scope.schedules[id].scheduleData !== undefined)
        {
            self._setScheduleData(id);
            $scope.loadedSchedule = true;
            $scope.save_allowed = false;
        }
    },

    /*This function set single schedule data from loaded schedules
     * wors directly with scope
     **/
    _setScheduleData: function(id)
    {
        var self = this;
        var $scope = self.$scope;
        if (self.$scope.schedules[id].scheduleData !== undefined)
        {
            var scheduleData = angular.fromJson(self.$scope.schedules[id].scheduleData);

            $scope.schedule.scheduleName = scheduleData.scheduleName;
            $scope.schedule.emailFrom    = (scheduleData.emailFrom !== undefined ? scheduleData.emailFrom : '');
            $scope.schedule.emailTo      = (scheduleData.emailTo   !== undefined ? scheduleData.emailTo   : '');
            $scope.schedule.scheduleCSV  = (scheduleData.scheduleCSV   !== undefined ? scheduleData.scheduleCSV   : false);
            $scope.schedule.schedulePDF  = (scheduleData.schedulePDF   !== undefined ? scheduleData.schedulePDF   : false);
            $scope.schedule.skipMailing  = (scheduleData.skipMailing   !== undefined ? scheduleData.skipMailing   : 0);

            $scope.schedule.reportTimeType = (scheduleData.reportTimeType !== undefined ? scheduleData.reportTimeType : '');
            $scope.schedule.dayNumber      = (scheduleData.dayNumber      !== undefined ? scheduleData.dayNumber : '');
            $scope.schedule.dayName        = (scheduleData.dayName        !== undefined ? scheduleData.dayName : '');
            $scope.schedule.singleDay      = (scheduleData.singleDay      !== undefined ? scheduleData.singleDay : '');
            $scope.schedule.hour           = (scheduleData.hour           !== undefined ? scheduleData.hour : '');
            $scope.schedule.minute         = (scheduleData.minute         !== undefined ? scheduleData.minute : '');

            $scope.schedule.outputReportTitle       = (scheduleData.outputReportTitle       !== undefined ? scheduleData.outputReportTitle : '');
            $scope.schedule.outputReportDescription = (scheduleData.outputReportDescription !== undefined ? scheduleData.outputReportDescription : '');



            if (self.$scope.schedules[id].hostcontexts !== undefined  && !angular.equals({}, self.$scope.schedules[id].hostcontexts) )
            {
                $scope.savedHostcontextsprofileid = self.$scope.schedules[id].hostcontextsprofileid;
                $scope.savedHostcontextspath      = self.$scope.schedules[id].hostcontextspath;
                $scope.savedHostcontexts          = self.$scope.schedules[id].hostcontexts;
            }

            if (self.$scope.schedules[id].excludedhosts !== undefined  && !angular.equals({}, self.$scope.schedules[id].excludedhosts) )
            {
              $scope.savedExcludedhosts         = JSON.parse(self.$scope.schedules[id].excludedhosts);
            }
        }
    },

    /**
     *isScheduled  -switch for the report types - advanced or scheduled - default advanced
     *isModal - is this is inside modal window - default true
     */
    saveSchedule: function(isOverwrite) {
        var self = this;

        var showOverwrite   = (isOverwrite !== true ? false : true);

        self._notificationService.resetNotification();

        if (self.validateScheduleParams() === false) {
            return false;
        }

        self._setLabelAndCategory();

        // prepare model to save
        var formData = {};

        // TODO: save report and then schedule, do not save all in one go
        // do not save environment stuff
        var SQLTOSAVE = angular.copy(self.$scope.SQL);

        delete SQLTOSAVE.hostcontexts;
        delete SQLTOSAVE.hostcontextsprofileid;
        delete SQLTOSAVE.hostcontextspath;
        delete SQLTOSAVE.excludedHosts;

        formData.SQL = angular.toJson(SQLTOSAVE);

        var timeTmp = self._getTimeClassAndText();

        var paramsToSend = {};


            paramsToSend.reportLabel      = (self.$scope.reportLabel    !== undefined && self.$scope.reportLabel.input !=='' ? self.$scope.reportLabel.input : '');
            paramsToSend.reportCategory   = (self.$scope.reportCategory !== undefined && self.$scope.reportCategory.input !=='' ? self.$scope.reportCategory.input : '');
            paramsToSend.sharedPermission = angular.toJson(self.$scope.reportRoles);
            paramsToSend.is_public = (self.$scope.is_public.input === true ? true : false);


            paramsToSend.scheduleName  = self.$scope.schedule.scheduleName;


            paramsToSend.scheduleTime  = timeTmp.scheduledReportTimeClass;

            paramsToSend.scheduleHumanReadableTime = timeTmp.scheduledReportHumanReadableTime;

            paramsToSend.emailFrom     = self.$scope.schedule.emailFrom;
            paramsToSend.emailTo       = (self.$scope.schedule.emailTo !== undefined ? self.$scope.schedule.emailTo : '');
            paramsToSend.skipMailing  =   (self.$scope.schedule.skipMailing !== undefined ? self.$scope.schedule.skipMailing : '0');

            paramsToSend.outputFileType            = self._getOutputType();

            paramsToSend.outputReportTitle         = self.$scope.schedule.outputReportTitle;
            paramsToSend.outputReportDescription   = self.$scope.schedule.outputReportDescription;

            paramsToSend.search_params = encodeURIComponent(self.$scope.SQL.SQLSTRING);

            paramsToSend.overwrite     = showOverwrite;


            //save new schedule environment or old
            if (self.$scope.saveContext === true) {
                paramsToSend.hostcontextsprofileid = self.$scope.hostcontextsprofileid  !== undefined ? self.$scope.hostcontextsprofileid   : false;
                paramsToSend.hostcontextspath      = self.$scope.hostcontextspath       !== undefined ? self.$scope.hostcontextspath        : false;
                paramsToSend.hostcontexts          = self.$scope.hostcontexts           !== undefined ? self.$scope.hostcontexts            : false;
                paramsToSend.excludedHosts          = self.$scope.excludedHosts           !== undefined ? self.$scope.excludedHosts            : false;
            }
            else if (self.$scope.savedEnvironment !== undefined && angular.equals({}, self.$scope.savedEnvironment)) {
                paramsToSend.hostcontextsprofileid = self.$scope.savedHostcontextsprofileid !== undefined ? self.$scope.savedHostcontextsprofileid  : false;
                paramsToSend.hostcontextspath      = self.$scope.savedHostcontextspath      !== undefined ? self.$scope.savedHostcontextspath       : false;
                paramsToSend.hostcontexts          = self.$scope.savedHostcontexts          !== undefined ? self.$scope.savedHostcontexts           : false;
                paramsToSend.excludedHosts          = self.$scope.excludedHosts           !== undefined ? self.$scope.excludedHosts            : false;
            }

            paramsToSend.scheduleData        = angular.toJson( self.$scope.schedule);
            paramsToSend.AdvancedReportsData = formData;

        var data = $.param(paramsToSend);

        self._reportService.saveScheduleForReport(data).then(
            function(result) {
                self._notificationService.setNotification('success', result.data);
                self.$scope.reportId = result.data[0].reportId;

                self.$scope.showOverwrite = false;

                // clear form to initial
                self._initializeSheduleData();
                self.setPristine(self.$scope.scheduleForm);
                self.$scope.saveContext  = false;
                self.$scope.savedEnvironment = {};

                self._refreshScheduleList();
            },
            function(error) {
                self._notificationService.setNotification('error', error.data);
                if(error.data[0]['errorCode'] === 422) {
                    self.$scope.showOverwrite = true;
                }
            });
        unbindBeforeUnload();
    },
    deleteSchedule: function(id) {
        var self = this;
        var $scope = self.$scope;
        $("<div></div>")
            .dialog_modal({
                passedArgs: ["Delete this schedule?", [
                    //buttons
                    {
                        "label":"Cancel",
                        "class":"btn-large"
                    },
                    {
                        "label":"Delete",
                        "class":"btn-large btn-primary",
                        "callback": function(){
                            var paramsToSend = {};

                            paramsToSend.reportId   = self.$scope.reportId ;
                            paramsToSend.scheduleId = id;

                            var data = $.param(paramsToSend);

                            if (id !== '')
                            {
                                self._reportService.deleteSchedule(data).then(
                                    function(result) {
                                        self._notificationService.setNotification('success', result.data);
                                        self._refreshScheduleList();
                                    },
                                    function(error) {
                                        self._notificationService.setNotification('error', error.data);
                                    });
                            }
                        }
                    },
                ],
                    {
                        header:"<h1>Delete schedule</h1>"
                    }],

            })
    },
    // -------------- Initialization -----------------
    /*
     * Prepare all scopes
     */
   _initializeSheduleData: function() {
        var self = this;
        var $scope = self.$scope;

        $scope.schedule = {};

        var currentDateTime = new Date();
        var k = 0;

        $scope.showSchedule      = false;
        $scope.scheduleOverwrite = false;

        $scope.scheduleLists = [];
        $scope.scheduleLists.reportTimeTypesList = ["monthly", "weekly", "daily", "once"];

        $scope.schedule.reportTimeType = $scope.scheduleLists.reportTimeTypesList[0];



        var days_numbers = [];
        var label = '';
        for(k=1; k<32; k++)
        {
            if(k === 1 || k===21 || k=== 31) {
                label =k+'st';
            }
            else if(k === 2 || k === 22) {
                label = k+'nd';
            }
            else if(k === 3) {
                label = k+'rd';
            }
            else {
                label = k+'th';
            }
            days_numbers.push({
                'value': 'Day'+k,
                'label': label
            });
        }

        $scope.scheduleLists.dayNumbersList = days_numbers;
        //set current day number
        $scope.schedule.dayNumber = days_numbers[(currentDateTime.getUTCDate()-1)].value;
        $scope.schedule.humanDayNumber = days_numbers[(currentDateTime.getUTCDate()-1)].label; // Use label in human readable schedule list

        //javascript start week from Sunday
        $scope.scheduleLists.dayNameList = ['Sunday', 'Monday', 'Tuesday','Wednesday','Thursday','Friday','Saturday'];
        $scope.schedule.dayName          = $scope.scheduleLists.dayNameList[currentDateTime.getUTCDay()];


        var hours = [];
        for (k=0; k<24; k++)
        {
            hours.push({
                'value': 'GMT_Hr'+k,
                'label': k.toString()
                });
        }

        $scope.scheduleLists.hoursList = hours;
        $scope.schedule.hour           = hours[currentDateTime.getUTCHours()].value;


        var minutes = new Array();
        for (k=0; k<56; k=k+5)
        {
            minutes.push({
                'value': self._getCorrectMinClass(k),
                'label': k + '-' + (k+5)
                });
        }
        $scope.scheduleLists.minutesList = minutes;

        var current_minutes    = (Math.floor((currentDateTime.getUTCMinutes())/10)*10);
        $scope.schedule.minute = self._getCorrectMinClass(current_minutes);


        //defaultReportTitle and emailFrom set on php side and load from template
        $scope.schedule.outputReportTitle       = (defaultReportTitle       !== '' ? defaultReportTitle       : '');
        $scope.schedule.outputReportDescription = self._getDefaultReportDescription();

        $scope.schedule.emailFrom = (emailFrom        !== '' ? emailFrom        : '');

        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!

        var yyyy = today.getFullYear();

        if(dd < 10)
        {
            dd = '0'+ dd;
        }
        if(mm < 10){
            mm = '0' + mm;
        }

        $scope.schedule.singleDay = yyyy + '-'  + mm + '-' + dd;
        setTimeout(processPageBeforeLeave, 1000);
    },

    _getDefaultReportDescription: function() {
        return "CFEngine SQL reports";
    },

    _getCorrectMinClass: function ($val) {
        var result = '';

        switch ($val) {
            case 0 :
                result = 'Min00_05';
                break;
            case 5 :
                result = 'Min05_10';
                break;
            case 55:
                result = 'Min55_00';
                break;

            default:
                result = 'Min'+$val + '_' + ($val+5);
        }
        return result;
    },

    /* called from jQuery, used to set proper data on schedule - once */
   updateDayField: function(val) {
        var self = this;
        var $scope = self.$scope;
        $scope.schedule.singleDay = val;
    },

    validateReportTypeCheckboxes: function() {
        var self = this;
        var $scope = self.$scope;
        if($scope.schedule.schedulePDF === true || $scope.schedule.scheduleCSV === true) {
            $scope.validation.showreportTypeWarning = false;
            return true;
        }
        return false;
    },

    validateForm: function() {
        var self = this;
        // this check is for ng-disabled, thats why conditions should be opossite
        if (self.$scope.scheduleForm.$invalid === false && self.validateReportTypeCheckboxes() === true)
        {
            return false;
        }
        return true;
    },

    _refreshScheduleList: function() {
        var self = this;
        var $scope = self.$scope;
            $scope.schedules    = {};

        self._reportService.loadSchedules(self.$scope.reportId).then(
            function(result) {
                if (!self._commonHelper._isObjEmpty(result.data) && result.data !== null && result.data !== 'null')
                {
                    self._constructSchedulesList(result.data);
                }
                else
                {
                    self.$scope.schedules = {};
                }
            },
            function(error) {
                self._notificationService.setNotification('error', error.data)
            });
    },
    // build array, where key => id and data - schedule item info
    _constructSchedulesList: function(data) {
        var self = this;
        var $scope = self.$scope;
        self.$scope.schedules = {};
        // php report null as string
        if (!self._commonHelper._isObjEmpty(data) && data !== null && data !== 'null' )
        {
            angular.forEach(data , function(field, fieldId){
                field.scheduleData = angular.fromJson(field.scheduleData);
                self.$scope.schedules[field.id] = field;
            });
        }
    },
    cancelSchedule: function() {
        var self = this, url = '';
        if (self.$scope.savedSearchCategory && self.$scope.savedSearchCategory.input && self.$scope.savedSearchCategory.input  !== 'inventory') {
            url = '/report/run';
        } else {
            url = '/inventory/run';
        }

        if (self.$scope.reportId) {
            url += '/'+self.$scope.reportId;
        }
        unbindBeforeUnload();

        // do not add report id because user can edit loaded report
        self.$location.path(url);
    },
    checkIfObjEmpty: function (val)
    {
       var self = this;
       return self._commonHelper._isObjEmpty(val);
    },
     /*
     * When user clicks on public report checkbox
     */
    publicReport_disableRoles: function() {
        var self = this;
        var $scope = self.$scope;
        self._commonHelper.publicReport_disableRoles($scope.is_public.input, $scope);
    },
    // when user clicks on roles
    roles_disablePublicReport: function() {
        var self = this;
        var $scope = self.$scope;
        self._commonHelper.roles_disablePublicReport($scope.is_public.input, $scope);
    },
    setPristine: function(form) {

        if(form.$setPristine){//only supported from v1.1.x
            form.$setPristine();
        }else{

            /*
                 *Underscore looping form properties, you can use for loop too like:
                 *for(var i in form){
                 *  var input = form[i]; ...
                 */
            _.each(form, function (input)
            {
                if (input.$dirty) {
                    input.$dirty = false;
                }
            });
        }
    },

// save schedule functions




    /**
     * return report type
     *
     * @returns {String}
     */
    _getOutputType: function() {
        var  self = this, outputFileType = '';

        if(self.$scope.schedule.scheduleCSV !== undefined && self.$scope.schedule.scheduleCSV !== false)
        {
            outputFileType = 'csv';
        }

        if(self.$scope.schedule.schedulePDF !== undefined && self.$scope.schedule.schedulePDF !== false)
        {
            if (outputFileType.length > 0) {
                outputFileType +=',';
            }
            outputFileType += 'pdf';
        }

        return outputFileType;
    },

    /**
     *
     * @returns object with time class and human readable value
     */
    _getTimeClassAndText: function() {
        var  self = this, scheduledReportTimeClass = '', scheduledReportHumanReadableTime = '';
        var monthList=new Array();
            monthList[0]="January";
            monthList[1]="February";
            monthList[2]="March";
            monthList[3]="April";
            monthList[4]="May";
            monthList[5]="June";
            monthList[6]="July";
            monthList[7]="August";
            monthList[8]="September";
            monthList[9]="October";
            monthList[10]="November";
            monthList[11]="December";

        switch(self.$scope.schedule.reportTimeType) {
            case 'monthly' :
                scheduledReportTimeClass = '(' + monthList.join('|') + ').'+ self.$scope.schedule.dayNumber + '.';
                var day_number = self.$scope.schedule.dayNumber.replace("Day", "");
                self.$scope.schedule.humanDayNumber = self.$scope.scheduleLists.dayNumbersList[day_number-1].label;
                scheduledReportHumanReadableTime = "Monthly" + ' ' + self.$scope.schedule.humanDayNumber;
                break;
            case 'weekly'  :
                scheduledReportTimeClass = self.$scope.schedule.dayName + '.';
                scheduledReportHumanReadableTime = "Every " + self.$scope.schedule.dayName;
                break;
            case 'daily'   :
                scheduledReportHumanReadableTime = "Every day";
                break;
            case 'once'    :
                var tmp_date = $.trim(self.$scope.schedule.singleDay);
                var parsed_date = tmp_date.split('-');
                // convert everyting to integer, and we need day without 0 in front
                var intYear  = parseInt(parsed_date[0], 10);
                var intMonth = parseInt(parsed_date[1], 10);
                var intDay   = parseInt(parsed_date[2], 10);

                scheduledReportTimeClass = 'Yr'+intYear + '.' + monthList[(intMonth - 1)] + '.Day'+intDay + '.';

                scheduledReportHumanReadableTime =  "Once: " + intYear + ' ' + monthList[(intMonth - 1)] + ' ' + intDay;

                break;
        }

        scheduledReportTimeClass +=  self.$scope.schedule.hour + '.' + self.$scope.schedule.minute;

        scheduledReportHumanReadableTime += " " + self.$scope.schedule.hour.replace("GMT_Hr","") + ':' + self.$scope.schedule.minute.replace("Min","").replace("_","-");

        return  {'scheduledReportTimeClass': scheduledReportTimeClass, 'scheduledReportHumanReadableTime': scheduledReportHumanReadableTime};
    },


    validateScheduleParams: function() {
        var  self = this, error =  {};

        if (
            self.$scope.savedSearchCategory.input != 'compliance_report' &&
            (
                self.$scope.SQL.SQLSTRING === '' ||
                self.$scope.SQL.SQLSTRING === undefined
            )
        ) {
            error = self._notificationService.createObjectForNotification('error', 500, 'SQL query is missing. Please return to previous step');
            self._notificationService.setNotification(error.type, error.data)
            return false;
        }
        else if (self.validateReportTypeCheckboxes() === false ) {
            error = self._notificationService.createObjectForNotification('error', 500, 'Please select a report type');
            self._notificationService.setNotification(error.type, error.data)
            return false;
        }
        else if (self.$scope.schedule.reportTimeType === 'once')
        {
            var rgxp = /^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$/;
            if(rgxp.test($.trim(self.$scope.schedule.singleDay)) === false || $.trim(self.$scope.schedule.singleDay) === '')
            {
                error = self._notificationService.createObjectForNotification('error', 500, 'Invalid Report Date');
                self._notificationService.setNotification(error.type, error.data)
                return false;
            }
        }
        else {
            self._notificationService.resetNotification();
        }
        return true;
    },


    // if this is not saved report, and we get there from result page.
    // we set report name as schedule name and category from savedSearchCategory
    _setLabelAndCategory: function() {
        var  self = this;
        if (self.$scope.reportLabel === undefined || self.$scope.reportLabel.input === '') {
            self.$scope.reportLabel = self.$scope.savedSearchName;
        }

        if (self.$scope.reportCategory === undefined || self.$scope.reportCategory.input === undefined || self.$scope.reportCategory.input === '') {
            self.$scope.reportCategory = self.$scope.savedSearchCategory;
        }
    }
});
scheduleController.$inject = [
                                '$scope',
                                '$location',
                                '$routeParams',
                                'reportService',
                                'wizardSharedService',
                                'commonHelper',
                                'notificationService',
                                'modalWindowService'
                            ];