package com.imofan.android.basic;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class MFOpenEvent {
    private final static String LOG_TAG = Mofang.LOG_TAG + "_MFOpenEvent";

    final static String TABLE_EVENT = "open";
    final static String FIELD_ID = "id";
    final static String FIELD_TIME = "time";
    final static String FIELD_APP_VERSION = "app_version";
    final static String FIELD_SEND = "send";

    final static String CREATE_SQL =
            "CREATE TABLE IF NOT EXISTS " + TABLE_EVENT + " (" +
                    FIELD_ID + " INTEGER PRIMARY KEY, " +
                    FIELD_TIME + " NUMERIC NOT NULL, " +
                    FIELD_SEND + " INTEGER DEFAULT 0);";

    final static String UPGRADE_SQL =
            "ALTER TABLE " + TABLE_EVENT + " ADD COLUMN " + FIELD_APP_VERSION + " TEXT DEFAULT '';";

    private int id;
    private long time = System.currentTimeMillis();     //�¼�����ʱ��
    private String appVersion;
    private boolean send = false;                      //�Ƿ��Ѿ����͸�����

    //�Զ�������ݿ����ΪEvent����
    static MFOpenEvent parse(Cursor cur) {
        MFOpenEvent event = new MFOpenEvent();
        if(cur.getColumnIndex(FIELD_ID) > -1) {
            event.setId(cur.getInt(cur.getColumnIndex(FIELD_ID)));
        }
        if(cur.getColumnIndex(FIELD_TIME) > -1) {
            event.setTime(cur.getLong(cur.getColumnIndex(FIELD_TIME)));
        }
        if(cur.getColumnIndex(FIELD_APP_VERSION) > -1) {
            event.setAppVersion(cur.getString(cur.getColumnIndex(FIELD_APP_VERSION)));
        }
        if(cur.getColumnIndex(FIELD_SEND) > -1) {
            event.setSend(cur.getInt(cur.getColumnIndex(FIELD_SEND)) == 1);
        }
        return event;
    }

    //��Event����־û�����ݿ���
    //��Ϊ�¼�������update�Ŀ��ܣ��ʸ÷�����ֻ����insert
    private void persist(MFDatabaseManager dbManager) {
        SQLiteDatabase database = dbManager.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(FIELD_TIME, this.getTime());
        cv.put(FIELD_APP_VERSION, this.getAppVersion());
        cv.put(FIELD_SEND, this.isSend() ? 1 : 0);
        database.insert(TABLE_EVENT, null, cv);
    }

    static String[] getAppVersions(MFDatabaseManager dbManager, boolean send) {
        String where = " where " + MFOpenEvent.FIELD_SEND + "=?";
        String[] params = new String[1];
        if(send) {
            params[0] = "1";
        } else {
            params[0] = "0";
        }

        SQLiteDatabase db = dbManager.getReadableDatabase();
        Cursor cur = null;
        try {
            cur = db.rawQuery("select distinct " + MFOpenEvent.FIELD_APP_VERSION
                    + " from " + MFOpenEvent.TABLE_EVENT + where
                    + " order by " + MFOpenEvent.FIELD_APP_VERSION, params);
            if(cur.getCount() > 0) {
                String[] appVersions = new String[cur.getCount()];
                int i = 0;
                while(cur.moveToNext()) {
                    appVersions[i] = cur.getString(cur.getColumnIndex(FIELD_APP_VERSION));
                    i++;
                }
                return appVersions;
            }
        } finally {
            if(cur != null) {
                cur.close();
            }
        }
        return null;
    }

    //��ȡĳ���¼�ĳ����������
    static List<MFOpenEvent> getEvents(MFDatabaseManager dbManager, String appVersion, boolean send) {
        String where = " where " + MFOpenEvent.FIELD_APP_VERSION + "=? and " + MFOpenEvent.FIELD_SEND + "=?";
        String[] params = new String[2];
        if(appVersion == null) {
            params[0] = "";
        } else {
            params[0] = appVersion;
        }
        if(send) {
            params[1] = "1";
        } else {
            params[1] = "0";
        }

        SQLiteDatabase db = dbManager.getReadableDatabase();
        Cursor cur = null;
        try {
            cur = db.rawQuery("select * from " + MFOpenEvent.TABLE_EVENT + where
                    + " order by " + MFOpenEvent.FIELD_TIME, params);
            if(cur.getCount() > 0) {
                List<MFOpenEvent> events = new ArrayList<MFOpenEvent>(cur.getCount());
                while(cur.moveToNext()) {
                    events.add(MFOpenEvent.parse(cur));
                }
                return events;
            }
        } finally {
            if(cur != null) {
                cur.close();
            }
        }
        return null;
    }

    //����¼����
    static void addEvent(MFDatabaseManager dbManager, String appVersion, long time) {
        MFOpenEvent ev = new MFOpenEvent();
        ev.setAppVersion(appVersion);
        ev.setTime(time);

        try {
            ev.persist(dbManager);
            if(Mofang.DEBUG) {
                Log.d(LOG_TAG, "[addOpenEvent]" + ev);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //�����ʷ�¼����
    static void clearHistoryEvents(MFDatabaseManager dbManager, int date) {
        SQLiteDatabase database = dbManager.getWritableDatabase();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        try {
            long millionSeconds = dateFormat.parse(Integer.toString(date)).getTime();
            database.delete(TABLE_EVENT, FIELD_SEND + "=? and " + FIELD_TIME + "<?",
                    new String[]{"1", Long.toString(millionSeconds)});
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if(Mofang.DEBUG) {
            Log.d(LOG_TAG, "[clearHistoryOpenEvents]" + date);
            LogUtils.writeLog("Clear Open events success!");
        }
    }

    //����¼��ѷ���
    static void signSentEvent(MFDatabaseManager dbManager, List<Integer> idList) {
        SQLiteDatabase db = dbManager.getWritableDatabase();

        LogUtils.writeLog("Sign Open events: "+idList);

        for(int id : idList) {
            ContentValues cv = new ContentValues();
            cv.put(MFOpenEvent.FIELD_SEND, "1");
            db.update(MFOpenEvent.TABLE_EVENT, cv, "id=?", new String[]{Integer.toString(id)});
        }

        if(Mofang.DEBUG) {
            Log.d(LOG_TAG, "[signSentEvent]");
            LogUtils.writeLog("Sign Open events success!");
        }
    }

    @Override
    public String toString() {
        return "{id=" + id + ", time=" + time + ", appVersion=" + appVersion + ", send=" + send + "}";
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    public String getAppVersion() {
        return appVersion;
    }

    public void setAppVersion(String appVersion) {
        this.appVersion = appVersion;
    }

    public boolean isSend() {
        return send;
    }

    public void setSend(boolean send) {
        this.send = send;
    }
}
