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;
import android.util.Log;
/**
 * 网络数据分析
 * @author Rex
 *
 */
public class MFNetworkInfo {
	private static final String TAG = "MFNetworkInfo";
	
    final static String TABLE = "netspeed_detail_data";  				 //网络数据分析表
    
    final static String FIELD_ID = "id";
    final static String FIELD_URI = "uri";        			        //网络访问地址
    final static String FIELD_TYPE = "request_type";                //0 : 单一文件http请求， 1: 整个web页面请求
    final static String FIELD_START_DOWNLOAD = "start_download";    //开始任务的时间  
    final static String FIELD_DOWN_TYPE = "image_type";             //下载类型 1 ： 图片 ； 0：其它
    final static String FIELD_ACCESS = "access";        	        //网络访问类型
    final static String FIELD_DURATION = "duration";                //下载资源使用时间
    final static String FIELD_SIZE = "size";            	        //下载资源的大小
    final static String FIELD_STATUSCODE = "status_code";           //状态码
    final static String FIELD_FOREGIN_KEY = "foreign_key";          //关联应用表信息的主键 

    /**
     * c_id appid  deviceid  region start_time
     * 
     * id  uri time  size  access  c_id
     */
    
    /**
     * 初始化创建表SQL
     */
    final static String CREATE_SQL =
            "CREATE TABLE IF NOT EXISTS " + TABLE + " (" +
                FIELD_ID + " INTEGER PRIMARY KEY, " +
                FIELD_URI + " TEXT NOT NULL," +
                FIELD_TYPE + " INTEGER DEFAULT 0 ," +
                FIELD_START_DOWNLOAD + " INTEGER DEFAULT 0," +
                FIELD_DOWN_TYPE + " INTEGER DEFAULT 0 ," +
                FIELD_ACCESS + " TEXT NOT NULL, " +
                FIELD_SIZE + " INTEGER DEFAULT 0, " +
                FIELD_DURATION + " INTEGER DEFAULT 0," +
                FIELD_STATUSCODE + " INTEGER DEFAULT 0," +
                FIELD_FOREGIN_KEY + " INTEGER DEFAULT 0);";
    
    final static String DELETE_SQL = "DROP TABLE IF EXISTS network";
    

    
    /**
     * 解析数据库数据为MFNetworkInfo对象
     * @param cur
     * @return
     */
    static MFNetworkInfo parse(Cursor cur) {
    	MFNetworkInfo networkInfo = new MFNetworkInfo();
        if(cur.getColumnIndex(FIELD_ID) > -1) {
        	networkInfo.setId(cur.getInt(cur.getColumnIndex(FIELD_ID)));
        }
        if(cur.getColumnIndex(FIELD_URI) > -1) {
            networkInfo.setUrl(cur.getString(cur.getColumnIndex(FIELD_URI)));
        }
        if(cur.getColumnIndex(FIELD_TYPE) > -1) {
            networkInfo.setType(cur.getInt(cur.getColumnIndex(FIELD_TYPE)));
        }
        if(cur.getColumnIndex(FIELD_START_DOWNLOAD) > -1) {
            networkInfo.setStartTime(cur.getLong(cur.getColumnIndex(FIELD_START_DOWNLOAD)));
        }
        if(cur.getColumnIndex(FIELD_DOWN_TYPE) > -1) {
            networkInfo.setImageType(cur.getInt(cur.getColumnIndex(FIELD_DOWN_TYPE))==1 ? true : false);
        }
        if(cur.getColumnIndex(FIELD_ACCESS) > -1) {
        	networkInfo.setAccess(cur.getString(cur.getColumnIndex(FIELD_ACCESS)));
        }
        if(cur.getColumnIndex(FIELD_SIZE) > -1) {
        	networkInfo.setSize(cur.getLong(cur.getColumnIndex(FIELD_SIZE)));
        }
        if(cur.getColumnIndex(FIELD_DURATION) > -1) {
        	networkInfo.setDuration(cur.getLong(cur.getColumnIndex(FIELD_DURATION)));
        }
        if(cur.getColumnIndex(FIELD_STATUSCODE) > -1) {
        	networkInfo.setStatusCode(cur.getInt(cur.getColumnIndex(FIELD_STATUSCODE)));
        }
        if(cur.getColumnIndex(FIELD_FOREGIN_KEY) > -1) {
        	networkInfo.setForeignKey(cur.getInt(cur.getColumnIndex(FIELD_FOREGIN_KEY)));
        }
        return networkInfo;
    }

    //将MFNetworkInfo对象持久化到数据库中
    private void persist(MFDatabaseManager dbManager) {
        SQLiteDatabase database = dbManager.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(FIELD_URI, this.getUrl());
        cv.put(FIELD_TYPE, this.getType());
        cv.put(FIELD_START_DOWNLOAD,this.getStartTime());
        cv.put(FIELD_DOWN_TYPE, this.isImageType() ? 1 : 0);
        cv.put(FIELD_ACCESS, this.getAccess());
        cv.put(FIELD_SIZE, this.getSize());
        cv.put(FIELD_DURATION, this.getDuration());
        cv.put(FIELD_STATUSCODE, this.getStatusCode());
        cv.put(FIELD_FOREGIN_KEY, this.getForeignKey());
        database.insert(TABLE, null, cv);
    }
    
    /**
     * 添加网络信息
     * @param context
     * @param dbManager
     * @param requestType   请求类型  type:0 单一文件http请求， 1： 整个web页面请求
     * @param uri
     * @param startDownTime 任务开始下载时间
     * @param isImage       下载资源是否是图片
     * @param size          下载资源大小
     * @param duration      任务下载所需时间
     * @param statusCode    下载返回状态码
     * @param foreignKey    所关联主表id
     */
    static void addNetworkInfo(Context context,MFDatabaseManager dbManager, int requestType,String uri,long startDownTime,
            boolean isImageType,long size,long duration,int statusCode,int foreignKey){
    	if(dbManager==null) return;
    	MFNetworkInfo networkInfo = new MFNetworkInfo();
    	networkInfo.setType(requestType);
    	networkInfo.setUrl(uri);
    	networkInfo.setImageType(isImageType);
    	networkInfo.setStartTime(startDownTime);
    	String networkName = MFNetSpeedMonitor.getNetworkType(context);
    	networkInfo.setAccess((networkName==null ? "none" : networkName));
    	networkInfo.setSize(size);
    	networkInfo.setDuration(duration);
    	networkInfo.setStatusCode(statusCode);
    	networkInfo.setForeignKey(foreignKey);
    	try{
    		networkInfo.persist(dbManager);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    

    /**
     * 清空网络分析数据表
     * @param dbManager
     */
    static void clearNetworkInfo(MFDatabaseManager dbManager,int id) {
    	try{
    		SQLiteDatabase database = dbManager.getWritableDatabase();
    		database.delete(TABLE, FIELD_FOREGIN_KEY+" =? ", new String[]{String.valueOf(id)});
    		if(Mofang.DEBUG) {
    			Log.v(TAG,"Clear network info success!");
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    static List<MFNetworkInfo> getNetworkInfo(MFDatabaseManager dbManager,int id){
    	 SQLiteDatabase db = dbManager.getReadableDatabase();
         Cursor cur = null;
         try {
             cur = db.rawQuery("select * from " + TABLE + " where "+FIELD_FOREGIN_KEY+" =? ", new String[]{String.valueOf(id)});
             if(cur.getCount() > 0) {
                 List<MFNetworkInfo> networkInfos = new ArrayList<MFNetworkInfo>(cur.getCount());
                 while(cur.moveToNext()) {
                	 networkInfos.add(parse(cur));
                 }
                 return networkInfos;
             }
         }catch(Exception e){
        	 e.printStackTrace();
         } finally {
             if(cur != null) {
                 cur.close();
             }
         }
    	
    	return null;
    }
	
	private int id;
	private String access;          //访问方式 "wifi","gprs","hspa",读不到为 "none"
	private String url;             //网络请求接口
	private int type;               //类型
	private long startTime;         //开始下载时间
	private boolean isImageType;    //下载资源类型是否是图片
	private long duration;			//下载时间  (单位: 秒)
	private long size;    	        //下载资源大小 （单位: k）
	private int statusCode;			//状态码
	private int foreignKey; 		//关联主表
	
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	public String getAccess() {
		return access;
	}
	
	public void setAccess(String access) {
		this.access = access;
	}
	
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
	public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }
    
	public long getStartTime() {
        return startTime;
    }

    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }

    public long getDuration() {
        return duration;
    }

    public void setDuration(long duration) {
        this.duration = duration;
    }
	
	public boolean isImageType() {
		return isImageType;
	}

	public void setImageType(boolean isImageType) {
		this.isImageType = isImageType;
	}

	public long getSize() {
		return size;
	}
	
	public void setSize(long size) {
		this.size = size;
	}

	public int getStatusCode() {
		return statusCode;
	}

	public void setStatusCode(int statusCode) {
		this.statusCode = statusCode;
	}

	public int getForeignKey() {
		return foreignKey;
	}

	public void setForeignKey(int foreignKey) {
		this.foreignKey = foreignKey;
	}
	
}
