function ScreenService(){
    if(arguments.callee._singletonInstance){
        return arguments.callee._singletonInstance;
    }
    arguments.callee._singletonInstance = this;

    var self = this; self.name = "ScreenService"; // MANDATORY
    
    this.screenDatas = [];
    this.screenControllers = [];
    this.screenCounter = 0;
    
    this.exceptionDatas = []; 
    this.exceptionList = [];
    this.exceptionCounter = 0;

    this.commandsControllers = [];
    self.lastCmdId = 0;

    this.screenStatusData = false;
    this.checkScreensTimer = null;

    this.intervals = {
        checkScreens : 20000,
        screenStatus : 20000,
        screenCommands : 10000    
    }
    this.timers = {
        checkScreens : 0,
        screenStatus : 0,
        screenCommands : 0
    }

    this.init = function(){
        self.update();
        if( !self.timers.screenStatus ){
            self.screenStatus();
        }
        if( !self.timers.screenCommands ){
            self.screenCommands();
        }
    }
    
    this.update = function () {
        self.log("Updating screens: ");
        var dow = self.getDayOfWeek();
        self.OS.readFile(self.OS.rootDir+self.ROUTES['XML'].path+dow+".xml",function(data,filename,params){
            var dataManager = new DataManagerController();
            $(dataManager).one("DataManagerControllerDataLoaded",{},self.onDataLoaded);
            $(dataManager).one("DataManagerControllerDataError",{},self.onDataError);
            dataManager.loadDataXML(data);
        });
        
    }
    
    this.loadExceptions = function ( callback ){
        if (self.exceptionDatas.length > 0 ){
            self.exceptionDatas.forEach ( function ( data ) {
                self.exceptionCounter++;
                var exception = self.processException ( data ); //self.OS.generateNewScreenController ( data, self.platform, self.screenCounter);

                if ( exception ){
                    this.push ( exception );
                }
            }, self.exceptionList )
        }
        callback();
    }

    this.loadScreens = function () { 
        clearInterval ( self.checkScreensTimer );
        console.log ( new Date() + ' - Screen Manager: Update screens: Start' );
        self.log ( new Date() + ' - Screen Manager: Update screens: Start' );
        self.screenControllers.forEach ( function (screenController ) {
            screenController.stop();
        })
        self.screenControllers = [];
        if (self.screenDatas.length > 0 ){
            self.screenDatas.forEach ( function ( data ) {
                self.screenCounter++;
                var controller = self.OS.generateNewScreenController ( data, self.exceptionList, self.screenCounter);
                if ( controller ){
                    this.push ( controller );
                }
            }, self.screenControllers )
            clearTimeout(self.checkScreensTimer);
            self.checkScreensTimer = setTimeout ( self.checkScreens, 5000);
        }
        console.log ( new Date() + ' - Screen Manager: Update screens: ' + self.screenControllers.length + ' screens' );
        self.log ( new Date() + ' - Screen Manager: Update screens: ' + self.screenControllers.length + ' screens' );
    }
    
    
    this.onDataLoaded = function(e){
        self.log("Load on DataManagerController for screens");
        //var xml = e.currentTarget.getScreens();

        self.screenDatas = e.currentTarget.getScreens();//.screens;
        self.exceptionDatas = e.currentTarget.getExceptions();//.exceptions;
        self.loadExceptions( self.loadScreens );

    };

    this.onDataError = function(e){
        self.log("Error on DataManagerController for screens");
        self.notifyError(self.ERROR['SCREEN_SERVICE']+16,self.name+": Function getScreens()  :  Error on DataManagerController for screens");
    };
    
    
    this.checkScreens = function  () {
        clearTimeout(self.checkScreensTimer);
        self.checkScreensTimer = setTimeout ( self.checkScreens, 5000);
        var status =[];
        try {
            self.screenControllers.forEach ( function ( controller ) {
                this.push ( controller.getStatus() );
            }, status )
        }catch (error){
            console.log(error);
            clearTimeout(self.checkScreensTimer);
            self.checkScreensTimer = setTimeout ( self.checkScreens, 5000);
        }
        try {
            if ( status.length > 0 ){
                self.screenStatusData = status
            }else{
                self.screenStatusData = false
            }
        }catch (error){
            console.log(error);
            clearTimeout(self.checkScreensTimer);
            self.checkScreensTimer = setTimeout ( self.checkScreens, 5000);
        }
        
        clearTimeout(self.checkScreensTimer);
        self.checkScreensTimer = setTimeout ( self.checkScreens, 5000);
    }
    
    //LEGACY
    this.getStatus = function (){
        return self.screenStatusData;
    }
    //END

    this.checkCommands = function () {

    }



    this.screenStatus = function(){
        clearTimeout(self.timers.screenStatus);
        if(self.screenDatas.length > 0){
            if(!self.OS.busy){
              self.log("# Screen status beat ... ");
              var data = self.getScreenStatusData();
              self.log("Sending screen status for player : "+self.core_id);
              self.api_connector.post(self.api_url,self.api_ver,"player/alive/devices",data,self.screenStatusResponse);
              self.timers.screenStatus = setTimeout(self.screenStatus,self.intervals.screenStatus);
            }else{
                self.timers.screenStatus = setTimeout(self.screenStatus,(self.intervals.screenStatus/5));
                self.log("# Screen status beat ... CANCELED ... OS is busy");
            }
        }
        else{
            self.timers.screenStatus = setTimeout(self.screenStatus,(self.intervals.screenStatus*15));
        }
        
    };
    
    this.screenStatusResponse = function(response,status,params){
        if(status == "success"){
            self.log("# Screen status response ... success");
            self.log('# Screen status response: ' + response);

          self.log(response);
        }
    };

    this.getScreenStatusData = function(){
        var data = {
            id: self.core_id
        }
        var devices = self.screenStatusData; //copy to avoid rewrite before stringify
        if ( devices ){
            data.devices = JSON.stringify(devices);
            self.log (data.devices);
        }
        return data;
    };

    this.screenCommands = function(){
        clearTimeout(self.timers.screenCommands);
        if(self.screenDatas.length > 0){
            if(!self.OS.busy ){
                if ( self.commandsControllers.length == 0) {
                    self.log("# Screen commands beat ... ");
                    var data = "id=" + self.core_id ;
                    self.log("Getting commands for player : " + self.core_id );
                    self.api_connector.post(self.api_url, "2.0", "player/screen_command_request",data,self.screenCommandsResponse);
                    self.timers.screenCommands = setTimeout(self.screenCommands,self.intervals.screenCommands);
                }else{
                    self.timers.screenCommands = setTimeout(self.screenCommands,(self.intervals.screenCommands/5));
                    self.log("# Screen commands get beat ... CANCELED ... command in progress");
                }
            }else{
                self.timers.screenCommands = setTimeout(self.screenCommands,(self.intervals.screenCommands/5));
                self.log("# Screen commands get beat ... CANCELED ... OS is busy");
            }
        }
        else{
            self.timers.screenCommands = setTimeout(self.screenCommands,(self.intervals.screenCommands*15));
        }
        
    };

    this.screenCommandsResponse = function(response,status,params){
        if(status == "success"){
          self.log("# Screen commands get response ... success");
          self.log('# Screen commands get response: ' + response);
          self.processCommand ( response );
          //TO DO test commands
        }
    };


    this.sendScreenCommands = function ( cmd ){
        self.log("Sending commands for player : " + self.core_id );
        data = "id=" + self.core_id +"&response=" + cmd.output + "&command_id=" + cmd.id ;
        self.log("Sending commands data: " + data );

        self.api_connector.post(self.api_url, "2.0", "player/screen_command_response",data,self.sendScreenCommandsResponse);
        self.commandsControllers.pop();
    }
    
    this.sendScreenCommandsResponse = function(response,status,params){
        if(status == "success"){
            self.log("# Screen commands send response ... success");
            self.log('# Screen commands send response: ' + response);
        }else {
            self.log("# Screen commands send response ... fail");
            self.log('# Screen commands send response: ' + response);
        }
    };


    this.processException = function ( exception ){
        var now = self.getDate();
        if ( self.compareDates( now, self.getDate(false, exception.day * 1000 ) ) ){
            exception.today = true;
            return exception;
        }
        else if ( self.compareDates ( now, self.getDate(false, (exception.day+(24*60*60)) * 1000 ) ) ){
            exception.today = false;
            return exception;
        }
        else {
            return false;
        }

        return false;
    }

    this.compareDates = function ( d1, d2 ) { return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() === d2.getDate(); }

    this.processCommand = function ( commandString ){
        if ( commandString != "|||"){
            var cmdArray = commandString.split("|");
            var cmd = {}
                cmd.input = cmdArray[0];
                cmd.model = parseInt ( cmdArray[1] );
                cmd.port = cmdArray[2];
                cmd.id = parseInt ( cmdArray[3] );
                cmd.output = "Accepted: Not Executed ";
            var screen = {};
                screen ['id']           = 0;
                screen ['remote_id']    = 0;
                screen ['port']         = cmd.port;
                screen ['model']        = cmd.model;
                screen ['schedule']     = "";            
                screen ['exceptions'] = [];
            if ( cmd.id > self.lastCmdId ){
                self.lastCmdId = cmd.id;
                //self.log ( 'Screen commands: Load Driver')
                var controller = self.OS.generateNewScreenController ( screen, self.exceptionList, self.platform, cmd.id);
                if ( controller ){
                    self.commandsControllers.push ( controller );
                    self.log ( 'Screen commands: Send to Driver')
                    controller.freeCommandParse (cmd, self.sendScreenCommands );
                }else {
                    cmd.output = "Denied: Screen model not available";
                    self.sendScreenCommands ( cmd );
                }
            }else {
                self.log ( 'Screen commands: Repeated Command')
            }
        } else{
            self.log ( 'Screen commands: No commands on server')
        }
    }


}
ScreenService.prototype = new BasicService();
