package com.imofan.android.basic;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class MFAPPBasicInfo {
	final static String TABLE = "netspeed_basic_info";     	    //应用相关信息表
    
    final static String FIELD_ID = "id";
    final static String FIELD_APPKEY = "appKey";   		//应用id
    final static String FIELD_DEVICEID = "deviceid";    //设备id
    final static String FIELD_MAC = "mac_address";      //设备MAC地址
    final static String FIELD_REGION = "region";    	//地区
    final static String FIELD_CARRIER = "carrier";      //运营商
    final static String FIELD_RECORD = "record";        //是否需要抽样 【1：true 0:false】
    final static String FIELD_MAX = "max";              //需要抽样的最大数量 【默认值为50】
    final static String FIELD_IMAGE = "image";          //是否需要抽样图片下载【1：true 0:false】
    final static String FIELD_TIME = "start_time";      //应用启动时间 
    final static String FIELD_SEND = "send";            //是否发送【1：发送 0：未发送】
    /**
     * 初始化创建表SQL
     */
    final static String CREATE_SQL =
            "CREATE TABLE IF NOT EXISTS " + TABLE + " (" +
                FIELD_ID + " INTEGER PRIMARY KEY, " +
                FIELD_APPKEY + " TEXT, " +
                FIELD_DEVICEID + " TEXT, " +
                FIELD_MAC + " TEXT, " +
                FIELD_REGION + " TEXT," +
                FIELD_CARRIER + " TEXT,"+
                FIELD_RECORD + " INTEGER DEFAULT 1,"+
                FIELD_MAX + " INTEGER DEFAULT 50,"+
                FIELD_IMAGE + " INTEGER DEFAULT 0,"+
                FIELD_TIME + " TEXT ,"+
                FIELD_SEND + " INTEGER DEFAULT 0)";

    final static String DELETE_SQL = "DROP TABLE IF EXISTS app_info";
    
    /**
     * 解析数据库数据为MFAPPInfo对象
     * @param cur
     * @return
     */
    static MFAPPBasicInfo parse(Cursor cur) {
    	MFAPPBasicInfo appInfo = new MFAPPBasicInfo();
        if(cur.getColumnIndex(FIELD_ID) > -1) {
        	appInfo.setId(cur.getInt(cur.getColumnIndex(FIELD_ID)));
        }
        if(cur.getColumnIndex(FIELD_APPKEY) > -1) {
        	appInfo.setAppKey(cur.getString(cur.getColumnIndex(FIELD_APPKEY)));
        }
        if(cur.getColumnIndex(FIELD_DEVICEID) > -1) {
        	appInfo.setDeviceId(cur.getString(cur.getColumnIndex(FIELD_DEVICEID)));
        }
        if(cur.getColumnIndex(FIELD_MAC) > -1) {
            appInfo.setMacAddress(cur.getString(cur.getColumnIndex(FIELD_MAC)));
        }
        if(cur.getColumnIndex(FIELD_REGION) > -1) {
        	appInfo.setRegion(cur.getString(cur.getColumnIndex(FIELD_REGION)));
        }
        if(cur.getColumnIndex(FIELD_CARRIER) > -1) {
        	appInfo.setCarrier(cur.getString(cur.getColumnIndex(FIELD_CARRIER)));
        }
        if(cur.getColumnIndex(FIELD_RECORD) > -1) {
            appInfo.setRecord(cur.getInt(cur.getColumnIndex(FIELD_RECORD))==1 ? true :false);
        }
        if(cur.getColumnIndex(FIELD_MAX) > -1) {
            appInfo.setMax(cur.getInt(cur.getColumnIndex(FIELD_MAX)));
        }
        if(cur.getColumnIndex(FIELD_IMAGE) > -1) {
            appInfo.setRecoImage(cur.getInt(cur.getColumnIndex(FIELD_IMAGE))==1 ? true :false);
        }
        if(cur.getColumnIndex(FIELD_TIME) > -1) {
        	appInfo.setStartTime(cur.getString(cur.getColumnIndex(FIELD_TIME)));
        }
        if(cur.getColumnIndex(FIELD_SEND) > -1) {
            appInfo.setSendStatus(cur.getInt(cur.getColumnIndex(FIELD_SEND)) ==1 ? true :false);
        }
        return appInfo;
    }

    
    /**
     * 
     *   FIELD_RECORD + " INTEGER DEFAULT 1,"+
                FIELD_MAX + " INTEGER DEFAULT 50,"+
                FIELD_IMAGE + " INTEGER DEFAULT 0,"+
                FIELD_TIME + " TEXT ,"+
                FIELD_SEND + " INTEGER DEFAULT 0)";
     * @param dbManager
     */
    //将MFNetworkInfo对象持久化到数据库中
    private void persist(MFDatabaseManager dbManager) {
        SQLiteDatabase database = dbManager.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(FIELD_APPKEY, this.getAppKey());
        cv.put(FIELD_DEVICEID, this.getDeviceId());
        cv.put(FIELD_MAC, this.getMacAddress());
        cv.put(FIELD_REGION, this.getRegion());
        cv.put(FIELD_CARRIER, this.getCarrier());
        cv.put(FIELD_RECORD,this.isRecord() ? 1 : 0);
        cv.put(FIELD_MAX,this.getMax());
        cv.put(FIELD_IMAGE,this.isRecoImage() ? 1 : 0);
        cv.put(FIELD_TIME, this.getStartTime());
        cv.put(FIELD_SEND, this.isSendStatus() ? 1 : 0);
        
        database.insert(TABLE, null, cv);
    }
    
    /***
     * 存储抽样的基础数据
     * @param context 
     * @param dbManager
     * @param region      地区（“省,市”）
     * @param starTime    启动时间 
     */
    static void addAppInfo(Context context,MFDatabaseManager dbManager,String region,String starTime){
    	if(dbManager==null) return;
    	MFAPPBasicInfo appInfo= new MFAPPBasicInfo();
    	appInfo.setAppKey(Mofang.getAppKey(context));
    	appInfo.setDeviceId(Mofang.getDevId(context));
    	appInfo.setMacAddress(MFNetSpeedMonitor.getDeviceMac(context));
    	appInfo.setRegion(region);
    	appInfo.setCarrier(MFNetSpeedMonitor.getCarrierName(context));
    	appInfo.setStartTime(starTime);
    	try{
    		appInfo.persist(dbManager);
    	}catch(Exception e){ 
    		e.printStackTrace();
    	}
    }
    
    /**
     * 清除发送成功的数据
     * @param dbManager
     * @param ids
     */
    static void clearData(MFDatabaseManager dbManager,List<Integer> ids){
    	try{
    		SQLiteDatabase database = dbManager.getWritableDatabase();
    		if(ids!=null && !ids.isEmpty()){
    			for(int id : ids){
    				database.delete(TABLE, FIELD_ID + "=?", new String[]{String.valueOf(id)});
    				MFNetworkInfo.clearNetworkInfo(dbManager, id);
    			}
    		}
    		
    		clearNorecordData(dbManager);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    /**
     * 清除不需要抽样的数据【在获取抽样接口数据之前，默认是否抽样状态为true】
     * @param dbManager
     */
    static void clearNorecordData(MFDatabaseManager dbManager){
        SQLiteDatabase db = dbManager.getReadableDatabase();
        Cursor cur = null;
        try{
            cur = db.rawQuery("select * from " + TABLE +" where "+FIELD_RECORD+" =?" ,
                    new String[]{"0"});
            if(null!=cur && cur.getCount() > 0) {
                List<MFAPPBasicInfo> appInfos = new ArrayList<MFAPPBasicInfo>(cur.getCount());
                while(cur.moveToNext()) {
                    appInfos.add(parse(cur));
                }
                if(null!=appInfos && !appInfos.isEmpty()){
                    SQLiteDatabase database = dbManager.getWritableDatabase();
                    for(MFAPPBasicInfo data : appInfos){
                        database.delete(TABLE, FIELD_ID + "=?", new String[]{String.valueOf(data.getId())});
                        MFNetworkInfo.clearNetworkInfo(dbManager, data.getId());
                    }
                }
            }
        }catch(Exception e){
        	e.printStackTrace();
        }finally{
            if(cur != null) {
                cur.close();
            }
        }
    }
    
    /**
     * 更新应用信息表
     * @param dbManager
     * @param id		主键
     * @param region    地区（"省,市"） 
     */ 
    static void updateAppInfo(MFDatabaseManager dbManager,String id,String region) {  
    	try{
    		SQLiteDatabase db = dbManager.getWritableDatabase();  
    		ContentValues contentValues = new ContentValues();  
    		contentValues.put(FIELD_REGION, region);  
    		db.update(TABLE, contentValues, "id=?",new String[]{id});  
    		
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }  
    
    static void signSendData(MFDatabaseManager dbManager,List<Integer> ids){
        if(ids==null || ids.isEmpty()) return;
        try{
        	SQLiteDatabase db = dbManager.getWritableDatabase();  
        	ContentValues cv;
        	for(int id : ids) {
        		cv = new ContentValues();
        		cv.put(FIELD_SEND, "1");
        		db.update(TABLE, cv, "id=?", new String[]{Integer.toString(id)});
        	}
        	
        }catch(Exception e){
        	e.printStackTrace();
        }
    }
    
    
    /**
     * 获取APP基础数据
     * @param dbManager
     * @return
     */
    static List<MFAPPBasicInfo> getMFappBasicInfos(MFDatabaseManager dbManager,String startTime){
        SQLiteDatabase db = dbManager.getReadableDatabase();
        Cursor cur = null;
        try {
            cur = db.rawQuery("select * from " + TABLE +" where "+FIELD_TIME+" <=? and "+FIELD_SEND+" =? and "+FIELD_RECORD+" =?" ,
                    new String[]{startTime,"0","1"});
            if(cur.getCount() > 0) {
                List<MFAPPBasicInfo> appInfos = new ArrayList<MFAPPBasicInfo>(cur.getCount());
                while(cur.moveToNext()) {
                	appInfos.add(parse(cur));
                }
                return appInfos;
            }
        }catch(Exception e){
        	e.printStackTrace();
        } finally {
            if(cur != null) {
                cur.close();
            }
        }
        return null;
    }
    
    /**
     * 根据启动时间获取信息
     * @param dbManager
     * @param startTime
     * @return
     */
    static MFAPPBasicInfo getAppInfoByTime(MFDatabaseManager dbManager,String startTime){
    	if(startTime==null || "".equals(startTime)) return null;
        SQLiteDatabase db = dbManager.getReadableDatabase();
        Cursor cur = null;
        try {
            cur = db.rawQuery("select * from " + TABLE + " where "+FIELD_TIME+"=?" , new String[]{startTime});
            if(cur.getCount() > 0) {
            	while(cur.moveToNext()){
            		return parse(cur);
            	}
            }
        }catch(Exception e) {
        	e.printStackTrace();
        }finally {
            if(cur != null) {
                cur.close();
            }
        }
    	return null;
    }
    
    /**
     * 更新抽样接口的数据 
     * @param dbManager
     * @param matchTime        批次时间 
     * @param isRecord         是否执行抽样     
     * @param max              需要抽样的数据量
     * @param isRecordImage    是否抽样图片下载
     */
    static void updateRecordInfo(MFDatabaseManager dbManager,String startTime,boolean isRecord,int max,boolean isRecordImage){
    	if(dbManager==null) return;
    	try{
    		SQLiteDatabase db = dbManager.getWritableDatabase();
    		ContentValues cv = new ContentValues();
    		cv.put(FIELD_RECORD, isRecord ? 1 : 0);
    		cv.put(FIELD_MAX, max);
    		cv.put(FIELD_IMAGE, isRecordImage ? 1 : 0);
    		db.update(TABLE, cv, FIELD_TIME+"=?", new String[]{startTime});
    	}catch(Exception e){
    		e.printStackTrace();
    	}
        
    }
	
	private int id;
	private String appKey; 			//应用id
	private String deviceId;	    //设备id
	private String macAddress;      //设备mac地址
	private String region;          //地区信息，格式“省，市”
	private String carrier;         //运营商  
	private boolean isRecord;       //是否抽样
	private int max;                //需要抽样的数量
	private boolean isRecoImage;    //是否抽样图片下载
	private String startTime;       //应用启动时间
	private boolean sendStatus;     //发送状态
	
	private List<MFNetworkInfo> networkInfos;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getAppKey() {
		return appKey;
	}
	public void setAppKey(String appKey) {
		this.appKey = appKey;
	}
	public String getDeviceId() {
		return deviceId;
	}
	public void setDeviceId(String deviceId) {
		this.deviceId = deviceId;
	}
	public String getMacAddress() {
        return macAddress;
    }
    public void setMacAddress(String macAddress) {
        this.macAddress = macAddress;
    }
    public String getRegion() {
    	if(region==null || "".equals(region)) return "";
		return region;
	}
	public void setRegion(String region) {
		this.region = region;
	}
	public String getCarrier() {
		if(carrier==null || "".equals(carrier)) return "";
		return carrier;
	}
	public void setCarrier(String carrier) {
		this.carrier = carrier;
	}
	public boolean isRecord() {
        return isRecord;
    }

    public void setRecord(boolean isRecord) {
        this.isRecord = isRecord;
    }

    public int getMax() {
        return max;
    }

    public void setMax(int max) {
        this.max = max;
    }

    public boolean isRecoImage() {
        return isRecoImage;
    }

    public void setRecoImage(boolean isRecoImage) {
        this.isRecoImage = isRecoImage;
    }

    public String getStartTime() {
		return startTime;
	}
	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public List<MFNetworkInfo> getNetworkInfos() {
		return networkInfos;
	}

	public void setNetworkInfos(List<MFNetworkInfo> networkInfos) {
		this.networkInfos = networkInfos;
	}

    public boolean isSendStatus() {
        return sendStatus;
    }
    public void setSendStatus(boolean sendStatus) {
        this.sendStatus = sendStatus;
    }
}
