(function(ext) {
    var device = null;
    var _rxBuf = [];
    
    var sensor_location = {
    	PF:1,
    	PB:2
    	};
    
    var moter_location = {
    	ML:1,
    	MR:2
    	};

  	var switchStatus = {
  		OFF:0,
		  ON:1
	    };
	
	  var colorStatus = {
	  	OFF:0,
	  	RED:1,
	  	GREEN:2,
	  	BLUE:3,
	  	YELLOW:4,
	  	PURPLE:5,
	  	CYAN:6,
	  	WHITE:7
	  	};
	  
  ext.resetAll = function(){
  	device.send([0xff, 0x55, 2, 0, 4]);
  };

  ext.runIQCar = function(){};

  ext.getTouch = function(){};
  
  ext.getLightSensor = function(){};
  
  ext.getIRBarrier = function(){};
  
  ext.getMoterCode = function(){};
  
  ext.getSound = function(){};
  
  ext.getTimer = function(){};
  
  ext.setTimer = function(){};
  
  ext.WaitSecs = function(){};
  
  ext.setBeepSwitch = function(){};
  
  ext.setBeepMSecs = function(){};
  
  ext.setLED = function(){};
  
  ext.setMoterCode = function(){};
  
  ext.setMoter = function(){};
  
  ext.setTurnLeft = function(){};
  
  ext.setTurnRight = function(){};
  
  ext.setMoveForward = function(){};

  ext.setMoveBack = function(){};
    
  function runPackage(){
		var bytes = [0xff, 0x55, 0, 0, 2];
		for(var i=0;i<arguments.length;i++){
			if(arguments[i].constructor == "[class Array]"){
				bytes = bytes.concat(arguments[i]);
			}else{
				bytes.push(arguments[i]);
			}
		}
		bytes[2] = bytes.length-3;
		device.send(bytes);
	}
	
  function getPackage(){
		var nextID = arguments[0];
		
		var bytes = [0xff, 0x55];
		bytes.push(arguments.length+1);
		bytes.push(0);
		bytes.push(1);
		for(var i=1;i<arguments.length;i++){
			bytes.push(arguments[i]);
		}
		device.send(bytes);
	}
	
	// Extension API interactions
    var potentialDevices = [];
    ext._deviceConnected = function(dev) {
        potentialDevices.push(dev);

        if (!device) {
            tryNextDevice();
        }
    }

    function tryNextDevice() {
        // If potentialDevices is empty, device will be undefined.
        // That will get us back here next time a device is connected.
        device = potentialDevices.shift();
        if (device) {
            device.open({ stopBits: 0, bitRate: 115200, ctsFlowControl: 0 }, deviceOpened);
        }
    }

    var watchdog = null;
    function deviceOpened(dev) {
        if (!dev) {
            // Opening the port failed.
            tryNextDevice();
            return;
        }
        device.set_receive_handler('IQCar',processData);
    };
    
	ext._deviceRemoved = function(dev) {
        if(device != dev) return;
        device = null;
    };

    ext._shutdown = function() {
        if(device) device.close();
        device = null;
    };

    ext._getStatus = function() {
        if(!device) return {status: 1, msg: 'IQCar disconnected'};
        if(watchdog) return {status: 1, msg: 'Probing for IQCar'};
        return {status: 2, msg: 'IQCar connected'};
    }
    
	var descriptor = {};
	ScratchExtensions.register('IQCar', descriptor, ext, {type: 'serial'});
})({});