package com.yutou.jianr_mg.views;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.qq.e.comm.util.StringUtil;
import com.umeng.analytics.MobclickAgent;
import com.yutou.jianr_mg.Adapters.ReModListAdapter;
import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Data.TMod;
import com.yutou.jianr_mg.Data.TModtag;
import com.yutou.jianr_mg.Interfaces.HttpInterface;
import com.yutou.jianr_mg.Network.HttpApi;
import com.yutou.jianr_mg.Network.HttpUtils;
import com.yutou.jianr_mg.R;
import com.yutou.jianr_mg.Tools.Log;
import com.yutou.jianr_mg.Tools.ModUtils;
import com.yutou.jianr_mg.Tools.Utils;
import com.zzhoujay.richtext.RichText;
import com.zzhoujay.richtext.ig.DefaultImageGetter;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by 58381 on 2018/1/26.
 */

public class ModActivity extends AppCompatActivity {
    private TMod tMod;
    private ImageView modImage, icon, collection_img;
    private TextView title, by, downloadText, richText;
    private LinearLayout tagsLayout;
    private FrameLayout collection, share, download;
    private ListView quote;

    private ImageLoader imageLoader;
    private Handler handler;
    private ModUtils modUtils;
    private KProgressHUD hud;

    private List<TMod> remods;
    private Context context;
    private Intent intent;
    private static final String TAG = "ModActivity";

    public ModActivity() {
        Log.i("初始化mod列表");
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mod);
        intent = getIntent();
        handler = new Handler();
        tMod = JSON.parseObject(intent.getStringExtra("mod"), TMod.class);
        String modId=intent.getStringExtra("modId");
        if(modId!=null){
           hud=Utils.showLoading(this,null,null);
           hud.show();
           initMod(modId);
        }else {
            init();
        }
    }
    private void init(){
        context = this;
        imageLoader = Utils.initImageLoader(context);
        modUtils = ModUtils.init(context);
        modUtils.setMod(tMod);
        initViews();
        initData(tMod);
        initTags(tMod.getId());
        getRemod();
        if(hud!=null&&hud.isShowing()){
            hud.dismiss();
        }
    }
    private void initMod(String modId){
        try {
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            array.put(modId);
            json.put("ids",array);
            HttpUtils.post(HttpApi.HOME_URL + HttpApi.MOD_MODS, json, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try{
                        JSONObject json=new JSONObject(string);
                        List<TMod> list=JSON.parseArray(json.getJSONArray("data").toString(), TMod.class);
                        if(list.size()>0){
                            tMod=list.get(0);
                            handler.post(() -> init());
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }

                @Override
                public void httpError(Exception e) {

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

    }
    private void initViews() {
        modImage = findViewById(R.id.ModImage);
        icon = findViewById(R.id.icon);
        collection_img = findViewById(R.id.collection_img);
        title = findViewById(R.id.title);
        by = findViewById(R.id.by);
        richText = findViewById(R.id.richText);
        tagsLayout = findViewById(R.id.tags);
        collection = findViewById(R.id.collection);
        share = findViewById(R.id.share);
        download = findViewById(R.id.download);
        downloadText = download.findViewById(R.id.downloadText);
        quote = findViewById(R.id.quote);
    }

    private void initData(final TMod tMod) {
        try {
            Log.i(TAG,"---------->" + AppData.appConfig.getDownloadhome() + tMod.getImage());
            Log.i(TAG,"---------->" + AppData.appConfig.getDownloadhome() + tMod.getIcon());
            if(StringUtil.isEmpty(tMod.getImage())){
                imageLoader.displayImage(AppData.appConfig.getDownloadhome() + tMod.getIcon(), modImage);
            }else {
                imageLoader.displayImage(AppData.appConfig.getDownloadhome() + tMod.getImage(), modImage);
            }
            imageLoader.displayImage(AppData.appConfig.getDownloadhome() + tMod.getIcon(), icon);
        }catch (Exception e){
            e.printStackTrace();
        }

        title.setText(tMod.getTitle());
        by.setText("@" + tMod.getByuser());
        by.setOnClickListener(v -> {

        });
        RichText.fromHtml(tMod.getInfo())
                .imageGetter(new DefaultImageGetter())
                //.type(RichType.html)
                .into(richText);
        downloadText.setTag(0);
        try {
            if (ModUtils.getModPath(tMod,"",true).listFiles().length > 0) {
                downloadText.setText("安装");
                downloadText.setTag(2);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        download.setOnClickListener(view -> downloadButtonClick());
        collection.setOnClickListener(view -> {
            if (Utils.testStringIsNull(AppData.Token)) {
                Utils.toast(context, "登录状态未知，请登录哦");
                return;
            }
            try {
                JSONObject json = new JSONObject();
                json.put("uid", AppData.user.getId());
                json.put("mid", tMod.getId() + "");
                HttpUtils.post(HttpApi.HOME_URL + HttpApi.MOD_COLLCETION, json, new HttpInterface() {
                    private String state = "收藏失败,未知错误";

                    @Override
                    public void httpGetData(String string, int code) {

                        try {
                            JSONObject json = new JSONObject(string);
                            if (json.getInt("code") == 100) {
                                switch (json.getInt("data")) {
                                    case 0:
                                        state = "收藏失败";
                                        break;
                                    case 1:
                                        state = "收藏成功";
                                        break;
                                    case -1:
                                        state = "提督您已经收藏过了哦";
                                        break;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.e(e,ModActivity.this);
                        }
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (state.equals("收藏成功")) {
                                    collection_img.setImageResource(R.drawable.icon_collection_ok);
                                }
                                Utils.toast(context, state);
                            }
                        });
                    }

                    @Override
                    public void httpError(Exception e) {

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(e, ModActivity.class);
            }
        });

    }

    private void getRemod() {
        remods = new ArrayList<>();
        try {
            JSONObject json = new JSONObject();
            json.put("mid", tMod.getId());
            json.put("remid", tMod.getRemod());
            HttpUtils.post(HttpApi.HOME_URL + HttpApi.MOD_REMOD, json, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try {
                        JSONObject json = new JSONObject(string);
                        if (json.getInt("code") == 100) {
                            remods = JSON.parseArray(json.getJSONArray("data").toString(), TMod.class);
                        }
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                ReModListAdapter adapter = new ReModListAdapter(context, remods);
                                quote.setAdapter(adapter);
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e(e,ModActivity.this);
                    }
                }

                @Override
                public void httpError(Exception e) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(e,ModActivity.this);
        }
    }

    private void downloadButtonClick() {
        switch (((int) downloadText.getTag())) {
            case -1:

                break;
            case 1:
                modUtils.reBackMod(tMod, (flag, type) -> Log.i(TAG, "还原mod：" + flag));

                break;
            case 0:
            case 2:
                modUtils.installMod(tMod, (flag, type) -> Log.i(TAG, "安装mod:" + flag));
                break;
        }
    }

    private void initTags(int mid) {
        try {
            JSONObject json = new JSONObject();
            json.put("mid", mid);
            HttpUtils.post(HttpApi.HOME_URL + HttpApi.MOD_TAG, json, new HttpInterface() {
                List<TModtag> tags;

                @Override
                public void httpGetData(String string, int code) {
                    Log.i(HttpApi.MOD_TAG, string);
                    try {
                        JSONObject json = new JSONObject(string);
                        if (json.getInt("code") == 100) {
                            tags = JSON.parseArray(json.getJSONArray("data").toString(), TModtag.class);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    for (TModtag tag : tags) {
                                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Utils.getPixelsFromDp(((Activity) context), 50), Utils.getPixelsFromDp(((Activity) context), 15));
                                        params.setMargins(Utils.getPixelsFromDp(((Activity) context), 10), 0, 0, 0);
                                        Button button = new Button(context);
                                        button.setText(tag.getTag());
                                        button.setTextSize(8);
                                        button.setBackgroundResource(R.drawable.frame_button);
                                        button.setLayoutParams(params);
                                        tagsLayout.addView(button);
                                    }

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

                    }
                }

                @Override
                public void httpError(Exception e) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
}
