package com.hh.holyolm;

import static android.content.ContentValues.TAG;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hh.holyolm.adapter.CommomRvAdapter;
import com.hh.holyolm.adapter.CommomRvViewHolder;
import com.hh.holyolm.model.CommandCardModel;
import com.hh.holyolm.model.LibModel;
import com.hh.holyolm.model.OptCardModel;
import com.hh.holyolm.util.XmlUtil;
import com.hh.holyolm.util.ZipUtils;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;


public class CommandCardLibFragment extends Fragment {


    public CommandCardLibFragment() {
        // Required empty public constructor
    }


    public static CommandCardLibFragment newInstance(String param1, String param2) {
        CommandCardLibFragment fragment = new CommandCardLibFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    View root;
    MainActivity parent;
    File libsDir;
    List<CommandCardModel> cardModelList;
    RecyclerView mRecyclerView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        root=inflater.inflate(R.layout.fragment_command_card_lib, container, false);
        parent=(MainActivity) getActivity();
        libsDir=parent.getLibsDir();

        mRecyclerView = (RecyclerView) root.findViewById(R.id.rv_com_lib);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        root.findViewById(R.id.btnSycComLib).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                queryLibs();
            }
        });

        loadData();


        return root;
    }

    private void queryLibs(){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String serverurl=prefs.getString("serverurl","");
        String url=serverurl+"?libtype=command";
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client =new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    Response response = client.newCall(request).execute();
                    if(response.code()==200){
                        String Data = response.body().string();
                        showData(Data);
                    }else{
                        showError(response.code());
                    }

                }catch (Exception e){
                    e.printStackTrace();
                    showError(e.getMessage());
                }
            }
        }).start();

    }
    private void showError(int code){
        parent.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(),"网络请求失败，错误代码："+code,Toast.LENGTH_LONG).show();
            }
        });
    }

    private void showError(String message){
        parent.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(),"网络请求失败，错误信息："+message,Toast.LENGTH_LONG).show();
            }
        });
    }
    int checkedItem=0;
    private void showData(final String data){
        parent.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //Toast.makeText(getContext(),data,Toast.LENGTH_LONG).show();
                Gson gson=new Gson();
                List<LibModel> libModelList=gson.fromJson(data,new TypeToken<List<LibModel>>(){}.getType());
                if(libModelList==null || libModelList.size()<1){
                    Toast.makeText(getContext(),"没有查询到已发布的库文件.",Toast.LENGTH_SHORT).show();
                    return;
                }

                String[] items=new String[libModelList.size()];
                for(int i=0;i<libModelList.size();i++){
                    items[i]=libModelList.get(i).getFilename();
                }


                AlertDialog.Builder builder = new AlertDialog.Builder(getContext())
                        .setTitle("选择已发布的库文件")
                        .setCancelable(false).setSingleChoiceItems(items,0, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Toast.makeText(getContext(), "你点击的内容为： " + items[i], Toast.LENGTH_LONG).show();
                                checkedItem=i;
                            }
                        });
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getContext(), "开始下载： " + libModelList.get(checkedItem).getFilename(), Toast.LENGTH_LONG).show();
                        downloadLib(libModelList.get(checkedItem));
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.create().show();
            }
        });
    }

    private void downloadLib(LibModel libModel){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client =new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(libModel.getDownloadurl())
                            .build();
                    Response response = client.newCall(request).execute();
                    if(response.code()==200){
                        //String Data = response.body().string();
                        byte[] bytes = response.body().bytes();
                        String folder=((MainActivity)getActivity()).getDownDir().getAbsolutePath();
                        String fullPath=folder+File.separator+libModel.getFilename();
                        Path filePath=Paths.get(fullPath);
                        if(Files.exists(filePath)){
                            Files.delete(filePath);
                        }
                        //Path filePath = Paths.get(folder + libModel.getFilename());
                        Files.write(filePath, bytes, StandardOpenOption.CREATE);
                        unzipLib(fullPath);
                    }else{
                        showError(response.code());
                    }

                }catch (Exception e){
                    e.printStackTrace();
                    showError(e.getMessage());
                }
            }
        }).start();
    }

    private void unzipLib(String filePath){
        File file=new File(filePath);
        if(file.exists() && file.getName().toLowerCase().endsWith(".zip")){
            try {
                File libsdir=((MainActivity)getActivity()).getLibsDir();
                File todir=new File(libsdir.getAbsolutePath()+File.separator+"command");
                if(todir.exists()) todir.delete();
                todir.mkdirs();
                ZipUtils.unZipFile3(file,todir.getAbsolutePath()+File.separator);
                reloadData();
            } catch (IOException e) {
                Log.e(TAG, Log.getStackTraceString(e));
                throw new RuntimeException(e);
            }
        }
    }

    private void reloadData(){
        parent.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                loadData();
            }
        });
    }

    private void loadData(){
        cardModelList= XmlUtil.ReadCommandCardLib(libsDir.getAbsolutePath()+File.separator+"command");

        if(cardModelList==null){
            Toast.makeText(getContext(),"未找到库文件.",Toast.LENGTH_LONG).show();
            return;
        }

        CommomRvAdapter<CommandCardModel> adapter = new CommomRvAdapter<CommandCardModel>(getContext(), cardModelList, R.layout.list_item_command_card) {
            @Override
            protected void fillData(CommomRvViewHolder holder, int position, CommandCardModel model) {
                holder.setText(R.id.tv_type, model.getType());
                holder.setText(R.id.tv_window, model.getWindow());
                holder.setText(R.id.tv_subject, model.getSubject());
                holder.setText(R.id.tv_number, model.getNumber());
                holder.setText(R.id.tv_version, model.getVersion());
                holder.setText(R.id.tv_name, model.getName());
            }
        };
        adapter.setOnItemClickListener((view, position) -> {
            //String pdfFile=libsDir.getAbsolutePath()+File.separator+"action"+File.separator+ cardModelList.get(position).getPdfFile();
            //showPDF(pdfFile);
            Intent intent=new Intent(getContext(), ExecTaskActivity.class);
            intent.putExtra("PkgPath",cardModelList.get(position).getPackagePath());
            intent.putExtra("Model",ExecTaskActivity.USE_MODEL_TEMPLATE);
            startActivity(intent);
        });
        mRecyclerView.setAdapter(adapter);
    }
}