package com.yutou.nas.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.nas.Datas.Jellyfin.Episode;
import com.yutou.nas.Datas.Jellyfin.EpisodeData;
import com.yutou.nas.Datas.Jellyfin.ItemInfo;
import com.yutou.nas.Datas.Jellyfin.LibsItem;
import com.yutou.nas.bangumi.BangumiTools;
import com.yutou.nas.interfaces.DownloadInterface;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

public class JellyfinAPIManager {
    private List<LibsItem> mediaItem = new ArrayList<>();
    private static String userId="389438aeda0a4972ac66a23cbe5c289c";
    private static String token="7f8efec6c950415cbaa8a0b54b3a832b";

    public JellyfinAPIManager() {
        login();
        mediaItem = getAllItem();
    }

    public LibsItem getLibs(String key) {
        HashMap<String, String> header = getHeader();
        String httpText = HttpTools.https_get("http://"+ConfigTools.load(ConfigTools.CONFIG,"nas_ip",String.class)+":8096/Users/"+userId+"/Items", header);
        JSONObject json = JSON.parseObject(httpText);
        if (key == null) {
            return null;
        }
        JSONArray items = json.getJSONArray("Items");
        for (Object o : items) {
            LibsItem item = JSON.parseObject(o.toString(), LibsItem.class);
            if (item.getName().equals(key)) {
                return item;
            }
        }
        return null;
    }

    public ItemInfo getInfo(String id) {
        String http = HttpTools.https_get("http://"+ConfigTools.load(ConfigTools.CONFIG,"nas_ip",String.class)+":8096/Users/"+userId+"/Items/" + id, getHeader());
        return JSON.parseObject(http).toJavaObject(ItemInfo.class);
    }

    public List<LibsItem> getAllItem() {
        String http = HttpTools.https_get("http://"+ConfigTools.load(ConfigTools.CONFIG,"nas_ip",String.class)+":8096/Users/"+userId+"/Items?SortBy=SortName&SortOrder=Ascending&IncludeItemTypes=Series&Recursive=true&Fields=PrimaryImageAspectRatio%2CBasicSyncInfo&ImageTypeLimit=1&EnableImageTypes=Primary%2CBackdrop%2CBanner%2CThumb&ParentId=28e774baf8f2fd279e7d58da9890a7d2", getHeader());
        JSONObject json = JSON.parseObject(http);

        JSONArray items = json.getJSONArray("Items");
        List<LibsItem> list =items.toJavaList(LibsItem.class);
        for (LibsItem item : list) {
            item.setInfo(getInfo(item.getId()));
        }
        return list;
    }

    public List<LibsItem> getLibsItems(String id) {
        String httpText = HttpTools.https_get("http://"+ConfigTools.load(ConfigTools.CONFIG,"nas_ip",String.class)+":8096/Users/"+userId+"/Items?ParentId=" + id, getHeader());
        JSONObject json = JSON.parseObject(httpText);
        JSONArray items = json.getJSONArray("Items");
        return items.toJavaList(LibsItem.class);
    }

    public JSONObject getItemShows(String id) {
        String data = HttpTools.https_get(String.format("http://"+ConfigTools.load(ConfigTools.CONFIG,"nas_ip",String.class)+":8096/Shows/%s/Seasons?userId="+userId+"",
                id
        ), getHeader());
        return JSON.parseObject(data);
    }

    public JSONObject getEpisodesForJson(String parentID, String id) {
        String data = HttpTools.https_get(String.format("http://"+ConfigTools.load(ConfigTools.CONFIG,"nas_ip",String.class)+":8096/Shows/%s/Episodes?seasonId=%s&userId="+userId+"",
                parentID,
                id
        ), getHeader());
        return JSON.parseObject(data);
    }

    public List<Episode> getEpisodes(String parentId, String id) {
        JSONObject json = getEpisodesForJson(parentId, id);
        JSONArray episodes = json.getJSONArray("Items");
        return episodes.toJavaList(Episode.class);
    }

    public JSONObject getEpisodesDataForJson(String id) {
        String data = HttpTools.https_get(String.format("http://"+ConfigTools.load(ConfigTools.CONFIG,"nas_ip",String.class)+":8096/Users/"+userId+"/Items/%s",
                id
        ), getHeader());
        return JSON.parseObject(data);
    }

    public EpisodeData getEpisodeData(String id) {
        return getEpisodesDataForJson(id).toJavaObject(EpisodeData.class);
    }

    public String getPathForEpisode(String parentId, String id) {
        List<Episode> list = getEpisodes(parentId, id);
        if (!list.isEmpty()) {
            return getEpisodeData(list.get(0).getId()).getPath();
        }
        return null;
    }


    public void uploadImage(File image, String id, String model) {
        try {
            HashMap<String, String> header = getHeader();
            header.put("Content-Type", "image/jpeg");
            String url = String.format("http://"+ConfigTools.load(ConfigTools.CONFIG,"nas_ip",String.class)+":8096/Items/%s/Images/%s",
                    id,
                    model
            );
            //url="http://tools.yutou233.cn/public/request.do";
            HttpTools.http_post(
                    url,
                    Base64.getEncoder().encode(StreamTools.fileToByte(image)),
                    4,
                    header

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

    public void saveJellyfinMetaData(JSONObject info, LibsItem item) {
        JSONArray airDate = new JSONArray();
        airDate.add(info.getString("air_date"));
        JSONObject providerIds = new JSONObject();
        providerIds.put("Imdb", "");
        providerIds.put("Tmdb", "");
        providerIds.put("Zap2It", "");
        JSONObject metadata = new JSONObject();
        metadata.put("Id", item.getId());
        metadata.put("Name", info.getString("name_cn"));
        metadata.put("OriginalTitle", info.getString("name"));
        metadata.put("ForcedSortName", "");
        metadata.put("CommunityRating", info.getJSONObject("rating").getFloat("score") + "");
        metadata.put("CriticRating", "");
        metadata.put("IndexNumber", "null");
        metadata.put("AirsBeforeSeasonNumber", "");
        metadata.put("AirsAfterSeasonNumber", "");
        metadata.put("AirsBeforeEpisodeNumber", "");
        metadata.put("ParentIndexNumber", "null");
        metadata.put("DisplayOrder", "");
        metadata.put("Album", "");
        metadata.put("AlbumArtists", new JSONArray());
        metadata.put("ArtistItems", new JSONArray());
        metadata.put("Overview", info.getString("summary"));
        metadata.put("Status", "");
        metadata.put("AirDays", new JSONArray());
        metadata.put("AirTime", "");
        metadata.put("Genres", new JSONArray());
        metadata.put("Tags", new JSONArray());
        metadata.put("Studios", new JSONArray());
        metadata.put("PremiereDate", "null");
        metadata.put("DateCreated", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(new Date()));
        metadata.put("EndDate", "null");
        metadata.put("ProductionYear", info.getString("air_date").split("-")[0]);
        metadata.put("AspectRatio", "");
        metadata.put("Video3DFormat", "");
        metadata.put("OfficialRating", "14+");
        metadata.put("CustomRating", "");
        metadata.put("People", BangumiTools.getPeople(info.getInteger("id")));
        metadata.put("LockData", false);
        metadata.put("LockedFields", new JSONArray());
        metadata.put("ProviderIds", providerIds);
        // metadata.put("Path", path);
        metadata.put("PreferredMetadataLanguage", "");
        metadata.put("PreferredMetadataCountryCode", "");
        metadata.put("RunTimeTicks", 0);
        metadata.put("Taglines", new JSONArray());
        HashMap<String, String> headers = getHeader();
        headers.put("Content-Type", "application/json");
        String ret = HttpTools.http_post("http://"+ConfigTools.load(ConfigTools.CONFIG,"nas_ip",String.class)+":8096/Items/" + item.getId()
                , metadata.toString().replace("\"null\"", "null").getBytes(StandardCharsets.UTF_8)
                , 4
                , headers);
        HttpTools.download(
                info.getJSONObject("images").getString("large").replace("http:", "https:"),
                item.getName() + "_poster.jpg",
                new DownloadInterface() {
                    @Override
                    public void onDownload(File file) {
                        super.onDownload(file);
                        uploadImage(file, item.getId(), "Primary");
                        JSONObject items = getItemShows(item.getId());
                        for (Object o : items.getJSONArray("Items")) {
                            JSONObject json = (JSONObject) o;
                            uploadImage(file, json.getString("Id"), "Primary");
                        }

                    }
                }
        );
    }

    public HashMap<String, String> getHeader() {
        HashMap<String, String> header = new HashMap<>();
        header.put("X-Emby-Authorization", "MediaBrowser Client=\"Jellyfin Web\", Device=\"Chrome\", DeviceId=\"TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzg2LjAuNDI0MC43NSBTYWZhcmkvNTM3LjM2fDE2MDI4NDYzMDc5NjE1\", Version=\"10.8.1\",Token=\""+token+"\"");
        return header;
    }


    public void testItem(String id) {
        JellyfinAPIManager manager = new JellyfinAPIManager();
        LibsItem item = manager.getLibs("番剧");
        if (item != null) {
            List<LibsItem> list;
            list = manager.getLibsItems(item.getId());
            for (LibsItem libsItem : list) {
                if ("轻音少女".equals(libsItem.getName())) {
                   /* saveJellyfinMetaData(
                            BangumiTools.getBangumiInfo(1424),
                            libsItem
                    );*/
                    System.out.println("libsItem = " + libsItem);
                    System.out.println(manager.getItemShows(libsItem.getId()));
                    JSONObject json = manager.getItemShows(libsItem.getId());
                    JSONArray array = json.getJSONArray("Items");
                    for (Object o : array) {
                        JSONObject _json = (JSONObject) o;
                        System.out.println(_json.getString("Name"));

                        if (_json.getString("Name").equals("第一季")) {
                            LibsItem _item = JSON.parseObject(_json.toJSONString(), LibsItem.class);
                            manager.saveJellyfinMetaData(
                                    BangumiTools.getBangumiInfo(1424),
                                    _item
                            );
                        } else if (_json.getString("Name").equals("第二季")) {
                            LibsItem _item = JSON.parseObject(_json.toJSONString(), LibsItem.class);
                            manager.saveJellyfinMetaData(
                                    BangumiTools.getBangumiInfo(3774),
                                    _item
                            );
                        } else if (_json.getString("Name").contains("[剧场版]")) {
                            LibsItem _item = JSON.parseObject(_json.toJSONString(), LibsItem.class);
                            manager.saveJellyfinMetaData(
                                    BangumiTools.getBangumiInfo(12426),
                                    _item
                            );
                        }


                    }
                  /*  System.out.println("libsItem = " + libsItem);
                    testItem(libsItem.getId());*/
                }
            }
        }
    }

    public JSONArray getAnimPaths() {
        JSONArray array = new JSONArray();
        for (LibsItem item : mediaItem) {
            JSONObject json = new JSONObject();
            json.put("name", item.getInfo().getName());
            List<LibsItem> list = getLibsItems(item.getId());
            json.put("size",list.size());
            JSONArray _items = new JSONArray();
            if (list.size() > 1) {
                for (LibsItem libsItem : list) {
                    JSONObject _item = new JSONObject();
                    _item.put("name", libsItem.getName());
                    _item.put("path", getInfo(libsItem.getId()).getPath());
                    _items.add(_item);
                }
                json.put("path",_items);
            }
            json.put("root",item.getInfo().getPath());
            array.add(json);
        }
        return array;
    }
    public void refresh(){
        String url="http://"+ConfigTools.load(ConfigTools.CONFIG,"nas_ip",String.class)+":8096/Items/28e774baf8f2fd279e7d58da9890a7d2/Refresh?Recursive=true&ImageRefreshMode=Default&MetadataRefreshMode=Default&ReplaceAllImages=false&ReplaceAllMetadata=false";
        String tmp=HttpTools.http_post(url,null,1,getHeader());
        System.out.println(tmp);
    }

    public void init(File path,String id) {
        if (id != null) {
            for (LibsItem item : mediaItem) {
                List<LibsItem> _temp = getLibsItems(item.getId());
                if (_temp.size() == 1) {
                    if (item.getInfo().getPath().contains(path.getPath())) {
                        System.out.println(item.getName() + " " + id);
                        new JellyfinAPIManager().saveJellyfinMetaData(BangumiTools.getBangumiInfo(Integer.parseInt(id)), item);
                        break;
                    }
                } else {
                    System.out.println(item.getName() + " > " + _temp.size());
                    for (LibsItem libsItem : _temp) {
                        ItemInfo info = getInfo(libsItem.getId());
                        if (info.getPath() != null) {
                            if (info.getPath().contains(path.getPath())) {
                                System.out.println("list > " + item.getName() + " " + id);
                                new JellyfinAPIManager().saveJellyfinMetaData(BangumiTools.getBangumiInfo(Integer.parseInt(id)), libsItem);
                                break;
                            }
                        } else {
                            String ep_Path = getPathForEpisode(info.getParentID(), info.getId());
                            if (ep_Path != null && ep_Path.contains(path.getPath())) {
                                System.out.println("list > " + item.getName() + " " + id);
                                new JellyfinAPIManager().saveJellyfinMetaData(BangumiTools.getBangumiInfo(Integer.parseInt(id)), libsItem);
                                break;
                            }
                        }
                    }
                }
                if (item.getInfo().getPath().contains(path.getPath())) {
                    System.out.println(item.getName() + " " + id);
                    new JellyfinAPIManager().saveJellyfinMetaData(BangumiTools.getBangumiInfo(Integer.parseInt(id)), item);
                    break;
                }
            }
        }
        /*for (File file : path.listFiles()) {
            if (file.isDirectory()) {
                // System.out.println("搜索目录:"+file.getAbsolutePath());
                init(file);
            }
        }*/

    }

    public static String mainPath = "Z:\\download\\anim\\";

    public void login(){
        String url="http://"+ConfigTools.load(ConfigTools.CONFIG,"nas_ip",String.class)+":8096/Users/authenticatebyname";
        HashMap<String, String> header=getHttpHeader();
        JSONObject json=new JSONObject();
        json.put("Pw","34864394");
        json.put("Username","home");
        String post = HttpTools.http_post(url, json.toJSONString().getBytes(StandardCharsets.UTF_8), 3, header);
        json=JSONObject.parseObject(post,JSONObject.class);
        token=json.getString("AccessToken");
        userId=json.getJSONObject("User").getString("Id");
    }
    private HashMap<String, String> getHttpHeader(){
        HashMap<String, String> header = new HashMap<>();
        header.put("content-type", "application/json");
        header.put("accept", "application/json");
        header.put("Connection", "keep-alive");
        header.put("User-Agent", HttpTools.getUa());
        header.put("Origin", "http://"+ConfigTools.load(ConfigTools.CONFIG,"nas_ip",String.class)+":8096");
        header.put("X-Emby-Authorization", "MediaBrowser Client=\"Jellyfin Web\", Device=\"Chrome\", DeviceId=\"TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzg2LjAuNDI0MC43NSBTYWZhcmkvNTM3LjM2fDE2MDI4NDYzMDc5NjE1\", Version=\"10.8.1\"");
        return header;
    }

    public static void main(String[] args) {
        File file = new File("Z:\\download\\anim\\神渣☆偶像");
        //new JellyfinAPIManager().search(file.getName(), file);
        JellyfinAPIManager manager = new JellyfinAPIManager();
          manager.init(file,"359985");
       // JSONArray search = manager.getAnimPaths();
       //     System.out.println(search);
    }
}
