package com.saki.ui.adapter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import com.saki.log.SQLog;
import com.saki.tools.FileUtil;
import com.saki.tools.ScriptUtil;
import com.saki.ui.ScriptUI;
import com.saki.ui.SwitchButton;
import com.saki.ui.listener.IPluginListener;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.saki.sqv9.R;
import com.saki.ui.view.DownloadButton;
import com.setqq.script.Script;
import com.setqq.script.ScriptLoader;

public class ScriptAdapter extends BaseAdapter implements IPluginListener {

    class ItemHolder {
        public ImageView icon;
        public TextView name;
        public TextView author;
        public TextView version;
        public TextView info;
        public SwitchButton opration;
        public DownloadButton download;
    }

    class PluginAdapterHandler extends Handler {
        public void add(Script p) {
            Message m = Message.obtain();
            m.obj = p;
            m.what = 0;
            sendMessage(m);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                Script p = (Script) msg.obj;
                replacePlugin(p);
                notifyDataSetChanged();
            } else if (msg.what == 1) {
                notifyDataSetChanged();
            } else {
                Script p = (Script) msg.obj;
                Iterator<Script> it = script.iterator();
                while (it.hasNext()) {
                    if (it.next().equals(p)) {
                        it.remove();
                        notifyDataSetChanged();
                        break;
                    }
                }
            }
        }

        public void remove(Script pn) {
            Message m = Message.obtain();
            m.obj = pn;
            m.what = 2;
            sendMessage(m);
        }

        private void replacePlugin(Script p) {
            Iterator<Script> it = script.iterator();
            while (it.hasNext()) {
                Script op = it.next();
                if (op.packageName.equals(p.packageName)) {
                    it.remove();
                    break;
                }
            }
            script.add(p);
        }

        public void update() {
            Message m = Message.obtain();
            m.what = 1;
            sendMessage(m);
        }
    }

    private final ArrayList<Script> script = new ArrayList<Script>();

    private final LayoutInflater inflater;

    private final PluginAdapterHandler handler = new PluginAdapterHandler();

    private final ScriptUI ui;

    public ScriptAdapter(Context c, ScriptUI ui) {
        inflater = LayoutInflater.from(c);
        this.ui = ui;
    }

    public void add(Script p) {
        ui.swipe.setRefreshing(false);
        handler.add(p);
    }

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

    @Override
    public Script getItem(int arg0) {
        return script.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ItemHolder holder;
        if (convertView == null) {
            holder = new ItemHolder();
            convertView = inflater.inflate(R.layout.item_plugin, null);
            holder.icon = convertView.findViewById(R.id.icon);
            holder.name = convertView.findViewById(R.id.name);
            holder.author = convertView.findViewById(R.id.author);
            holder.version = convertView.findViewById(R.id.version);
            holder.info = convertView.findViewById(R.id.info);
            holder.info.setMovementMethod(ScrollingMovementMethod.getInstance());
            holder.opration = convertView.findViewById(R.id.opration);
            holder.download = convertView.findViewById(R.id.down);
            convertView.setTag(holder);
        } else {
            holder = (ItemHolder) convertView.getTag();
        }
        final Script p = getItem(position);
        if (p.icon == null) {
            holder.icon.setImageResource(R.drawable.ic_plugin_face_default);
        } else {
            holder.icon.setImageDrawable(p.icon);
        }
        holder.name.setText(p.name);
        holder.author.setText(p.author);
        holder.version.setText(p.version);
        holder.info.setText(p.info);
        holder.opration.setChecked(p.opration);
        holder.opration.setOnCheckedChangeListener(p);
        if(p.type == 0) {
            holder.download.setVisibility(View.GONE);//隐藏更新
            holder.opration.setVisibility(View.VISIBLE);//显示开关
        }else if(p.type == 1){
            holder.download.setVisibility(View.VISIBLE);//显示下载
            holder.opration.setVisibility(View.GONE);//隐藏开关
        }else if(p.type == 2){
            holder.download.setVisibility(View.VISIBLE);//显示更新
            holder.download.setTitle("更新"); //更新标签
        }
        holder.download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                holder.download.startDownload(p.update, new DownloadButton.onDownload() {
                    @Override
                    public void complet(byte[] data) {
                        try {
                            String packname = ScriptUtil.unpackZip(new ByteArrayInputStream(data), FileUtil.SCRIPT_PATH);
                            ScriptLoader.load(FileUtil.SCRIPT_PATH,packname);
                        } catch (IOException e) {
                            SQLog.w("更新失败:"+p.update);
                        }
                    }
                });
            }
        });
        return convertView;
    }

    @Override
    public void onPluginAdd(Script p) {
        add(p);
    }

    @Override
    public void onPluginClear() {
        script.clear();
        handler.update();
    }

    @Override
    public void onFlush() {
        handler.update();
    }

    public void remove(Script p) {
        handler.remove(p);
    }

}
