package ai.pai.client.services;


import android.app.IntentService;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.android.common.http.HttpUtils;
import com.android.common.utils.JSONParseUtils;
import com.android.common.utils.LogHelper;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import ai.pai.client.R;
import ai.pai.client.utils.Constants;
import ai.pai.client.utils.UrlContainer;

/**
 * Created by chengzhenyu on 2015/9/2.
 */
public class UpgradeService extends IntentService {

    private static final String TAG = "UpgradeService";
    private Handler handler;

    public UpgradeService() {
        super(TAG);
        handler = new Handler(Looper.getMainLooper());
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        boolean isMuteUpdate = intent.getBooleanExtra("isMuteUpdate",true);
        try{
            String result = HttpUtils.doHttpPost(UrlContainer.CHECK_UPDATE_URL,null);
            LogHelper.d(TAG,"检查更新结果"+result);
            JSONObject json = new JSONObject(result);
            int status = json.getInt("status");
            if(status!=200){
                LogHelper.d(TAG,"检查更新失败");
                if(!isMuteUpdate){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), R.string.check_version_fail,Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                return;
            }
            JSONObject data = json.getJSONObject("data");
            JSONObject appInfo = data.getJSONObject("appinfo");
            String latestVersionCode = JSONParseUtils.getJSONString(appInfo.getString("latest_version_code"));
            int versionCode = Integer.parseInt(latestVersionCode);
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(),0);
            if(versionCode<=packageInfo.versionCode){
                LogHelper.d(TAG,"不需要更新");
                if(!isMuteUpdate){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), R.string.current_version_is_latest,Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                return;
            }
            String latestVersionUrl = JSONParseUtils.getJSONString(appInfo.getString("latest_url"));
            URL url = new URL(latestVersionUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(10000);
            conn.setRequestProperty("accept", "*/*");
            conn.connect();

            File dir = new File(Constants.APP_TEMP_DIR);
            dir.mkdirs();
            File file = new File(dir,"paiai"+System.currentTimeMillis()+".apk");
            LogHelper.d(TAG,"需要更新，开始下载，下载到："+file.getAbsolutePath());
            if(!isMuteUpdate){
                Toast.makeText(this, R.string.new_version_found,Toast.LENGTH_SHORT).show();
            }
            if(!file.exists()){
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(file);
            InputStream in =conn.getInputStream();
            int bufSize = 8192;
            int readLen = 0;
            int pos = 0;
            byte[] buffer = new byte[bufSize];
            while((readLen=in.read(buffer,pos,bufSize-pos))!=-1){
                out.write(buffer,pos,readLen);
                pos+=readLen;
                if(pos>=bufSize){
                    pos = 0;
                }
            }
            out.flush();
            in.close();
            out.close();
            conn.disconnect();
            Intent installIntent = new Intent();
            installIntent.setAction(Intent.ACTION_VIEW);
            installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            installIntent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            startActivity(installIntent);
        }catch (Exception e){
            if(!isMuteUpdate){
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.check_version_fail,Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

}
