'use strict';
import React, { Component } from 'react';
import {NativeModules,DeviceEventEmitter} from 'react-native'; 

const MethodModule = NativeModules.RNMethodModule;
const OVER_TIME = 5*1000;
const CONNECT_OVER_TIME = 35*1000;
const COMMAND_TIME_INTERVAL = 200;
const PROGRESS_TIME_INTERVAL =8*1000;
const TAG = 'RNDY';

if(__DEV__){
    const version = 201704011315;
    console.log(TAG,'dyg driver version:',version);
}

/** 监控的消息参数 */
const UPDATE_DEVICE_LIST = 'UPDATE_DEVICE_LIST';

let driver = null;

export default class RNADIDDriver{
    constructor(){
        this._eventMap = {

        };
        this._onUpdateDeviceList = null;
        this._onUpdateNewData = null;

        // this.startMonitorDriverEvent = this.startMonitorDriverEvent.bind(this);
        // this.endMonitorDriverEvent = this.endMonitorDriverEvent.bind(this);
        // this.startScan = this.startScan.bind(this);
        // this.stopScan = this.stopScan.bind(this);
        // this._timeoutPromise = this._timeoutPromise.bind(this);
        // this.connectDevice = this.connectDevice.bind(this);
        // this._mixTimeoutPromise = this._mixTimeoutPromise.bind(this);
        // this._executeEvent = this._executeEvent.bind(this);
        // this._registerEvent = this._registerEvent.bind(this);
        // this._commadTimeInterval = this._commadTimeInterval.bind(this);
        // this.createAuthChannel = this.createAuthChannel.bind(this);
        // this.disconnecAllDevicestWithout = this.disconnecAllDevicestWithout.bind(this);
        // this.getAllDataFromIndex = this.getAllDataFromIndex.bind(this);
        // this.disconnectDevice = this.disconnectDevice.bind(this);
    }

    /** 创建 */
    static shareDriver(){
        if(driver === null){
            driver = new RNADIDDriver();
        }

        return driver;
    }

    /** 开始扫描 */
    startScan(){
        console.log(TAG,'开始扫描');
        MethodModule.startScanDynamicGlucose();
        MethodModule.forceUpdateDeviceList();
    }

    /** 停止扫描 */
    stopScan(){
        console.log(TAG,'停止扫描');
        MethodModule.stopScanDynamicGlucose();
    }

    set onUpdateDeviceList(delegate){
        if(typeof delegate !== 'function'){
            throw  new Error('update device list must be a function');
        }

        this._onUpdateDeviceList = delegate;
    }

    set onUpdateNewData(delegate){
        if(typeof delegate !== 'function'){
            throw  new Error('update device list must be a function');
        }

        this._onUpdateNewData = delegate;
    }


    /** 断开连接 */
    disconnectDevice(deviceMac){
        MethodModule.disconnectDevice(deviceMac);
    }
    

    _mixTimeoutPromise(devicePromise){
        const timer = this._timeoutPromise(OVER_TIME);
        const mixPromise = Promise.race([devicePromise,timer]);
        return mixPromise;
    }

    _timeoutPromise(delay){
        return new Promise((resolve,reject)=>{
            setTimeout(()=>{
                reject(new Error('timeout'));
            },delay);
        });
    }

    _commadTimeInterval(interval){
        return new Promise((resolve,reject)=>{
            setTimeout(()=>{
                resolve('command await time out');
            },interval);
        });
    }

   
    _registerEvent(eventName){
        this._eventMap[eventName] = (deviceInfo)=>{
                console.log(TAG,'resolve '+eventName);
                resolve(deviceInfo);
            }       
    }

    _isFunctionEmpty(event){
        if(event===undefined || event===null){
            return true;
        }
        return false;
    }

    _executeEvent(eventName,deviceInfo){
        const event = this._eventMap[eventName];
            if(this._isFunctionEmpty(event)){
                return;
            }

            event(deviceInfo);
        this._eventMap[eventName] = null;
    }

    /** 监控底层驱动发送的消息 */
    startMonitorDriverEvent(){
        this._createChannel = (deviceInfo)=>{
            console.log(TAG,'created channel');
            this._executeEvent(DYG_CREATED_CHANNEL,deviceInfo);
        };
        DeviceEventEmitter.addListener(DYG_CREATED_CHANNEL,this._createChannel);


        this._onDoAuthorization = (deviceInfo)=>{
            console.log(TAG,'received '+DYG_ON_DO_AUTHORIZATION);
            this._executeEvent(DYG_ON_DO_AUTHORIZATION,deviceInfo);
        };
        DeviceEventEmitter.addListener(DYG_ON_DO_AUTHORIZATION,this._onDoAuthorization);


        this._onGetAllDataCount = (deviceInfo)=>{
            console.log(TAG,'received '+DYG_ON_GET_ALL_DATA_COUNT);
            this._executeEvent(DYG_ON_GET_ALL_DATA_COUNT,deviceInfo);
        };
        DeviceEventEmitter.addListener(DYG_ON_GET_ALL_DATA_COUNT,this._onGetAllDataCount);

        this._updateDeviceList = (deviceInfos)=>{
            // console.log(TAG,deviceInfos);
            if(this._onUpdateDeviceList === null){
                return;
            }
            const deviceList = deviceInfos.filter((device)=>{
                return device.deviceName.indexOf('TH-')>=0
            });

            this._onUpdateDeviceList(deviceList);
        }; 
        DeviceEventEmitter.addListener(UPDATE_DEVICE_LIST,this._updateDeviceList);

        /** 获得当前监控的状态 */
        this._onGetMonitorStatus = (deviceInfo)=>{
            this._executeEvent(DYG_ON_GET_MONITOR_STATUS,deviceInfo);
        }
        DeviceEventEmitter.addListener(DYG_ON_GET_MONITOR_STATUS,this._onGetMonitorStatus);

        /** 获得是否已经开始监控 */
        this._onStartMonitor = (deviceInfo)=>{
            this._executeEvent(DYG_ON_START_MONITOR,deviceInfo);
        }
        DeviceEventEmitter.addListener(DYG_ON_START_MONITOR,this._onStartMonitor);

        this._onStopMonitor = (deviceInfo)=>{
            this._executeEvent(DYG_ON_STOP_MONITOR,deviceInfo);
        }
        DeviceEventEmitter.addListener(DYG_ON_STOP_MONITOR,this._onStopMonitor);

        

        /** 监听接收到的单条新消息 */
        this._updateNewData = (deviceInfo)=>{
            if(this._onUpdateNewData === null){
                return;
            }

            this._onUpdateNewData(deviceInfo.index,deviceInfo.value);
        }
        DeviceEventEmitter.addListener(DYG_ON_UPDATE_NEW_DATA,this._updateNewData);

    }

    endMonitorDriverEvent(){
        DeviceEventEmitter.removeListener(DYG_CREATED_CHANNEL,this._createChannel);
        DeviceEventEmitter.removeListener(DYG_ON_DO_AUTHORIZATION,this._onDoAuthorization);
        DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA_COUNT,this._onGetAllDataCount);
        DeviceEventEmitter.removeListener(DYG_ON_GET_MONITOR_STATUS,this._onGetMonitorStatus);
        DeviceEventEmitter.removeListener(UPDATE_DEVICE_LIST,this._updateDeviceList);
        DeviceEventEmitter.removeListener(DYG_ON_START_MONITOR,this._onStartMonitor);
        DeviceEventEmitter.removeListener(DYG_ON_STOP_MONITOR,this._onStopMonitor);
        DeviceEventEmitter.removeListener(DYG_ON_UPDATE_NEW_DATA,this._updateNewData);
    }
}

