package com.hh.holyolm;

import static android.content.ContentValues.TAG;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
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.webkit.WebSettings;
import android.webkit.WebView;
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 OptCardLibFragment extends Fragment {


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

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

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

    }

    View root;
    MainActivity parent;
    File libsDir;
    List<OptCardModel> cardModelList;
    RecyclerView mRecyclerView;
    WebView webView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        root=inflater.inflate(R.layout.fragment_opt_card_lib, container, false);
        parent=(MainActivity) getActivity();
        libsDir=parent.getLibsDir();

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

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

        webView=root.findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);

        return root;
    }

    private void queryLibs(){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String serverurl=prefs.getString("serverurl","");
        String url=serverurl+"?libtype=action";
        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();

    }
    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 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();
            }
        });
    }

    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+"action");
                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.ReadOptCardLib(libsDir.getAbsolutePath()+File.separator+"action"+File.separator+"ActionCardLib.xml");

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

        CommomRvAdapter<OptCardModel> adapter = new CommomRvAdapter<OptCardModel>(getContext(), cardModelList, R.layout.list_item_opt_card) {
            @Override
            protected void fillData(CommomRvViewHolder holder, int position, OptCardModel model) {
                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).getDir()+File.separator+ cardModelList.get(position).getPdfFile();
            showPDF(pdfFile);
        });
        mRecyclerView.setAdapter(adapter);
    }

    private void showPDF(String file){
        Uri pdfUri=Uri.fromFile(new File(file));
        //Toast.makeText(ViewCardActivity.this,pdfUri.toString(),Toast.LENGTH_SHORT).show();
        webView.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + pdfUri.toString());
    }
}