package kr.co.icontrols.iotplatform;

import android.app.Application;
import android.content.Context;

import java.io.File;

import kr.co.icontrols.iotplatform.Database.DBUtil;
import kr.co.icontrols.iotplatform.Database.DatabaseHelper;
import kr.co.icontrols.iotplatform.Mqtt.MqttController;
import kr.co.icontrols.iotplatform.cognito.AppHelper;
import kr.co.icontrols.iotplatform.utils.SharedPrefUtil;

public class IotPlatformApplication  extends Application {

    public static final String TAG = IotPlatformApplication.class.getSimpleName();
    public static Context mContext;
    private static IotPlatformApplication instance;


    public static IotPlatformApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        instance = this;

        if (mContext == null) {
            mContext = getApplicationContext();

            //앱 저장소 생성
            SharedPrefUtil.init(mContext);

            //DB 생성
            DatabaseHelper.init(mContext);
            DBUtil.init(mContext);

            //Cognito 초기화
            AppHelper.init(mContext);

            //Mqtt 초기화
            MqttController.init(mContext);
        }
    }

    /**
     * 앱 캐시 삭제
     */
    public void clearApplicationData() {
        File cacheDirectory = getCacheDir();
        File applicationDirectory = new File(cacheDirectory.getParent());
        if (applicationDirectory.exists()) {
            String[] fileNames = applicationDirectory.list();
            for (String fileName : fileNames) {
                if (!fileName.equals("lib")) {
                    deleteFile(new File(applicationDirectory, fileName));
                }
            }
        }
    }

    /**
     * 파일 삭제 루틴.
     * @param file
     * @return
     */
    public static boolean deleteFile(File file) {
        boolean deletedAll = true;
        if (file != null) {
            if (file.isDirectory()) {
                String[] children = file.list();
                for (int i = 0; i < children.length; i++) {
                    deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
                }
            } else {
                deletedAll = file.delete();
            }
        }
        return deletedAll;
    }
}
