package com.zjut.gc502.mobilephonesafeprotector.cacheclear;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.text.format.Formatter;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zjut.gc502.mobilephonesafeprotector.R;
import com.zjut.gc502.mobilephonesafeprotector.cacheclear.adapter.CacheClearAdapter;
import com.zjut.gc502.mobilephonesafeprotector.cacheclear.entity.CacheInfo;
import com.zjut.gc502.mobilephonesafeprotector.cacheclear.utils.SetTitleUtil;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by ScienceHistory on 16/5/1.
 * 扫描缓存程序界面的逻辑代码,获取每个应用程序的缓存大
 * 然后累加起来一起展示,并展示扫描后的应用列表
 */
public class CacheClearListActivity extends Activity implements View.OnClickListener {
    protected static final int SCANNING = 200;
    protected static final int FINISH = 201;
    private AnimationDrawable animationDrawable;
    private TextView mRecommendCleanTv;//建议清理
    private TextView mCanClearTv; //可清理
    private long cacheMemory;
    private List<CacheInfo> cacheInfos = new ArrayList<>();
    private List<CacheInfo> mCacheInfos = new ArrayList<>();
    private PackageManager packageManager;
    private CacheClearAdapter adapter;
    private ListView mCacheLv;
    private Button mCacheBtn;
    private Thread thread;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SCANNING:
                    //mCacheBtn.setEnabled(false);
                    PackageInfo info = (PackageInfo) msg.obj;
                    mRecommendCleanTv.setText("正在扫描: "+info.packageName);
                    mCanClearTv.setText("已扫描缓存: "+
                            Formatter.formatFileSize(CacheClearListActivity.this,cacheMemory));
                    //在主线程添加变化后的集合
                    mCacheInfos.clear();
                    mCacheInfos.addAll(cacheInfos);
                    //ListView刷新
                    adapter.notifyDataSetChanged();
                    mCacheLv.setSelection(mCacheInfos.size());
                    break;
                case FINISH:
                    //扫描完毕,动画停止
                    animationDrawable.stop();
                    if (cacheMemory > 0) {
                        mCacheBtn.setEnabled(true);
                    } else {
                        mCacheBtn.setEnabled(false);
                        Toast.makeText(CacheClearListActivity.this,"您的手机洁净如新!",Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_cacheclearlist);
        packageManager = getPackageManager();
        initView();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        SetTitleUtil.setTitleStyle(this,"缓存扫描",R.color.cacheClearTitleColor);

        mRecommendCleanTv = (TextView) findViewById(R.id.tv_recommend_clean);
        mCacheBtn = (Button) findViewById(R.id.btn_clearall);
        mCacheBtn.setOnClickListener(this);
        mCanClearTv = (TextView) findViewById(R.id.tv_can_clean);
        mCacheLv = (ListView) findViewById(R.id.lv_scancache);
        animationDrawable = (AnimationDrawable) findViewById(R.id.imgv_broom).getBackground();
        animationDrawable.setOneShot(false);
        animationDrawable.start();
        adapter = new CacheClearAdapter(mCacheInfos,this);
        mCacheLv.setAdapter(adapter);
        fillData();
    }

    /**
     * 填充数据
     */
    private void fillData() {
        thread = new Thread() {
            @Override
            public void run() {
                //遍历手机中所有的应用程序
                cacheInfos.clear();
                List<PackageInfo> infos = packageManager.getInstalledPackages(0);
                for (PackageInfo info : infos) {
                    getCacheSize(info);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message msg = Message.obtain();
                    msg.obj = info;
                    msg.what = SCANNING;
                    handler.sendMessage(msg);
                }
                Message msg = Message.obtain();
                msg.what = FINISH;
                handler.sendMessage(msg);
            }
        };
        thread.start();
    }

    /**
     * 获取某个包名对应的应用程序的缓存大小
     * @param
     */
    public void getCacheSize(PackageInfo info) {
        try {
            Method method = PackageManager.class.getDeclaredMethod(
                    "getPackageSizeInfo",String.class,IPackageStatsObserver.class);
            method.invoke(packageManager,info.packageName,new MyPackObserver(info));

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        animationDrawable.stop();
        if (thread != null) {
            thread.interrupt();
        }
    }

    @Override
    public void onClick(View v) {
        if (cacheMemory > 0) {
            //跳转至清理缓存的页面Activity
            Intent i = new Intent(this,CleanCacheActivity.class);
            //将要清理的垃圾大小传递至另一个页面
            i.putExtra("cacheMemory",cacheMemory);
            startActivity(i);
            finish();
        }
    }

    private class MyPackObserver extends
            android.content.pm.IPackageStatsObserver.Stub {
        private PackageInfo info;
        public MyPackObserver(PackageInfo info) {
            this.info = info;
        }

        @Override
        public void onGetStatsCompleted(PackageStats pStats,boolean successd) throws RemoteException {
            long cachesize = pStats.cacheSize;
            if (cachesize >= 0) {
                CacheInfo cacheinfo = new CacheInfo();
                cacheinfo.setPackagename(info.packageName);
                cacheinfo.setCachesize(cachesize);
                cacheinfo.setAppname(info.applicationInfo.loadLabel(packageManager).toString());
                cacheinfo.setAppicon(info.applicationInfo.loadIcon(packageManager));
                cacheInfos.add(cacheinfo);
                cacheMemory += cachesize;
            }
        }
    }
}