package com.gh.gamecenter.common.utils;

import android.content.Context;
import android.text.TextUtils;

import com.gh.gamecenter.common.exposure.meta.MetaUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;

public class Installation {

    private static final String INSTALLATION = "INSTALLATION";

    private static String sID = null;

    public synchronized static String getUUID(Context context) {
        String imei = MetaUtil.getBase64EncodedIMEI();
        if (!TextUtils.isEmpty(imei)) {
            return imei;
        }
        String android_id = MetaUtil.getBase64EncodedAndroidId();
        if (!TextUtils.isEmpty(android_id)) {
            return android_id;
        }
        if (sID == null) {
            File installation = new File(context.getFilesDir(), INSTALLATION);
            try {
                if (!installation.exists())
                    writeInstallationFile(installation);
                sID = readInstallationFile(installation);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return sID;
    }

    private static void writeInstallationFile(File installation)
            throws IOException {
        try (FileOutputStream out = new FileOutputStream(installation)) {
            String id = UUID.randomUUID().toString();
            out.write(id.getBytes());
        }
    }

    private static String readInstallationFile(File installation)
            throws IOException {
        try (RandomAccessFile f = new RandomAccessFile(installation, "r")) {
            byte[] bytes = new byte[(int) f.length()];
            f.readFully(bytes);
            return new String(bytes);
        }
    }

}