package com.saki.ui;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;

import com.saki.QVMProtect;
import com.saki.qq.global.MsgManager;
import com.saki.service.NewConnection;
import com.saki.service.NewService;
import com.saki.tools.FileUtil;
import com.saki.tools.ScriptUtil;
import com.saki.ui.i.IB;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Toast;

import com.saki.sqv9.R;
import com.saki.plugin.dictionary.DictionaryView;
import com.setqq.script.javascript.JavaScript;
import com.setqq.script.lua.Lua;

public class PagerActivity extends Activity implements OnClickListener, IB {
    class Pager extends PagerAdapter {
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(list.get(position));
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return title[position];
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View v = list.get(position);
            container.addView(v);
            return v;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }
    }

    public TroopUI troop;
    public ScriptUI appView;
    public RuntimeLogUI set;
    public DictionaryView dictionary;
    private final LinkedList<View> list = new LinkedList<View>();
    private NewConnection connection;
    private final String[] title = new String[]{"群列表", "插件列表", "高级词库", "运行日志"};
    private long mExitTime;
    private ToastHandler toast = new ToastHandler(this);
    private boolean unPackScript(File path){
        try {
            ScriptUtil.unpackZip(path, FileUtil.SCRIPT_PATH);
        }catch (IOException e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       if(requestCode == FileUtil.SCRIPT_SELECT_CODE) {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                final String openPatch = FileUtil.getPath(this, uri);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        encodeLoad(openPatch);
                    }
                }).start();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    @QVMProtect
    private void encodeLoad(String openPatch){
        if(openPatch.endsWith(Lua.SUFFIX)||openPatch.endsWith(JavaScript.SUFFIX)) {
            toast.show("正在打包脚本，请稍后...");
            ScriptUtil util = new ScriptUtil(openPatch);
            if (util.checkScript()) {
                byte[] bin = ScriptUtil.packZip(util.getScriptFile(), util.getId() + "/");
                if (bin == null || bin.length == 0) {
                    toast.show("脚本打包失败");
                } else {
                    File zipFile = new File(util.getScriptFile().getParentFile() + "/" + util.getId() + ".zip");
                    FileUtil.writeFile(zipFile, bin);
                    //导入脚本
                    String msg = "脚本打包完成" + (unPackScript(zipFile) ? "且导入完毕" : "但导入失败");
                    toast.show(msg);
                }
            } else {
                toast.show("无法识别该脚本");
            }
        }else if(openPatch.endsWith(".zip")){
            toast.show("正在导入脚本，请稍后...");
            File zipFile = new File(openPatch);
            String msg = "脚本导入:" + (unPackScript(zipFile) ? "完毕" : "失败");
            toast.show(msg);
        }else{
            toast.show("未能识别的脚本文件类型");
        }
    }
    @Override
    public void onClick(View v) {
        if (v == appView.renameLua) {
            FileUtil.showFileChooser(this,FileUtil.SCRIPT_SELECT_CODE);
        }
        if (v == appView.encode) {
            FileUtil.showFileChooser(this,FileUtil.SCRIPT_SELECT_CODE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        troop = new TroopUI(this);
        MsgManager.getInstance().registerMsgListener(troop);
        appView = new ScriptUI(this);
        set = new RuntimeLogUI(this);
        dictionary = new DictionaryView(this);
        list.add(troop);
        list.add(appView);
        list.add(dictionary);
        list.add(set);
        setContentView(R.layout.activity_pager);
        ViewPager pager = findViewById(R.id.pager);
        pager.setAdapter(new Pager());
        bindService(new Intent(this, NewService.class),
                connection = new NewConnection(this), Context.BIND_AUTO_CREATE);
        appView.renameLua.setOnClickListener(this);
        appView.encode.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        troop.onDestroy();
        appView.onDestroy();
        set.onDestroy();
        unbindService(connection);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast t = Toast.makeText(this, "再按一次，退出程序", Toast.LENGTH_SHORT);
                t.setGravity(Gravity.CENTER, 0, 0);
                t.show();
                mExitTime = System.currentTimeMillis();
            } else {
                stopService(new Intent(this, NewService.class));
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBind(NewService service) {
    }

}
