package com.bonait.bnframework.common.helper;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.db.file.DBHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * SD卡操作
 */
public class SdCart {
    //region 单例模式
    private static SdCart  mInstance; //实例变量设置私有，防止直接通过类名访问

    private SdCart() { //默认构造函数私有，防止类外直接new创建对象
    }

    public static synchronized SdCart getInstance() { //静态同步方法作为唯一的实例对象获取方式
        if (mInstance==null) {
            mInstance = new SdCart();
        }
        return mInstance;
    }


    //endregion
    /**
     * 初始化数据库到SD卡
     */
    public void initSD() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
            ConfigName.getInstance().sdCardPath = sdDir.toString();
        }

        ConfigName.getInstance().appResRoot = ConfigName.getInstance().sdCardPath + "/hblxiaochaodb";
        ConfigName.getInstance().dbPath = ConfigName.getInstance().appResRoot + "/hbl.db";
        File rootFile = new File(ConfigName.getInstance().appResRoot);
        if (!rootFile.exists()) //创建目录
        { Log.i("日志",ConfigName.getInstance().sdCardPath);
            rootFile.mkdirs();
        }
        File file = new File(ConfigName.getInstance().dbPath);
        if(!file.exists())//文件不存在那么创建数据库
        {
            Log.i("日志","初始化数据库:文件不存在准备新建！");
            //1.复制本地文件到SD卡
            copyFilesFassets(ConfigName.getInstance().dishesCon, ConfigName.getInstance().dbPath);
            //2.创建数据库结构
            DBHelper.getInstance(ConfigName.getInstance().dishesCon).CreateTables();
        }
        Log.i("日志","初始化数据库目录:"+ConfigName.getInstance().dbPath);
    }

    /**
     * 从assets目录中复制整个文件夹内容
     *
     * @param context
     *            Context 使用CopyFiles类的Activity

     * @param newPath
     *            String 复制后路径 如：xx:/bb/cc
     */
    public void copyFilesFassets(Context context, String newPath) {
        try {
            // 如果是文件
            InputStream is = context.getAssets().open("hbl.db");
            FileOutputStream fos = new FileOutputStream(new File(newPath));
            byte[] buffer = new byte[1024];
            int byteCount = 0;
            while ((byteCount = is.read(buffer)) != -1) {// 循环从输入流读取 buffer字节
                fos.write(buffer, 0, byteCount);// 将读取的输入流写入到输出流
            }
            fos.flush();// 刷新缓冲区
            is.close();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}
