package com.yutou.nas.Controllers;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.nas.Services.impl.MusicToolsServiceImpl;
import com.yutou.nas.mybatis.model.MusicData;
import com.yutou.nas.utils.ConfigTools;
import com.yutou.nas.utils.RedisTools;
import com.yutou.nas.utils.StringUtils;
import com.yutou.nas.utils.Tools;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import static com.yutou.nas.Datas.AppData.defaultMusicPath;

@Controller
public class MusicController {

    @Resource
    MusicToolsServiceImpl musicTools;

    @RequestMapping("/nas/music/all.do")
    @ResponseBody
    public String getAllMusicList() {
        JSONObject json = new JSONObject();
        json.put("code", 0);
        json.put("scan", musicTools.isScan());
        json.put("size", musicTools.getLength());
        json.put("data", JSON.toJSON(musicTools.getMusicList(true)));
        return json.toJSONString();
    }

    @RequestMapping("/nas/music/list.do")
    @ResponseBody
    public String getMusicListOfPath(@RequestBody JSONObject body) {
        String path = body.getString("path");
        boolean type = body.containsKey("type") ? body.getBoolean("type") : false;
        if (StringUtils.isEmpty(path)
                || "root".equals(path)
                || !path.contains(defaultMusicPath)
        ) {
            path = defaultMusicPath;
        }
        com.yutou.nas.utils.Log.i("接收到地址:" + path);

        //path=path.replace(defaultMusicPath+File.separator,"");
        JSONObject json = new JSONObject();
        json.put("code", 0);
        json.put("scan", musicTools.isScan());
        json.put("size", musicTools.getLength());
        json.put("data", JSON.toJSON(musicTools.getPath(path, type, true)));
        return json.toJSONString();
    }

    @ResponseBody
    @RequestMapping("/nas/music/getAlbum.do")
    public String getAlbum(@RequestBody JSONObject body) {
        String album = body.getString("album");
        JSONObject json = new JSONObject();
        json.put("code", 0);
        if (StringUtils.isEmpty(album)) {
            json.put("data", JSON.toJSON(musicTools.getAllAlbum()));
        } else {
            json.put("data", JSON.toJSON(musicTools.selectAlbum(album, true)));
        }
        return json.toJSONString();
    }

    @ResponseBody
    @RequestMapping("/nas/music/getArtist.do")
    public String getArtist(@RequestBody JSONObject body) {
        String artist = body.getString("artist");
        JSONObject json = new JSONObject();
        json.put("code", 0);
        if (StringUtils.isEmpty(artist)) {
            json.put("data", JSON.toJSON(musicTools.getAllArtist()));
        } else {
            json.put("data", JSON.toJSON(musicTools.selectArtist(artist, true)));
        }
        return json.toJSONString();
    }

    @RequestMapping("/nas/music/reload.do")
    @ResponseBody
    public String reload() {
        JSONObject json = new JSONObject();
        musicTools.scanMusic();
        json.put("msg", "ok");
        json.put("code", 0);
        return json.toJSONString();
    }

    @RequestMapping("/nas/music/find/file.do")
    @ResponseBody
    public String findFile(@RequestBody JSONObject body) {
        String path = body.getString("path");

        JSONObject json = new JSONObject();
        if (StringUtils.isEmpty(path)) {
            json.put("code", -1);
            json.put("msg", "地址为空");
            return json.toJSONString();
        }
        json.put("code", 0);
        json.put("data", musicTools.getMusicDataOfMd5(path, true));
        return json.toJSONString();
    }

    @RequestMapping("/nas/music/getlocalhost.do")
    @ResponseBody
    public String getLocalHost() {
        JSONObject json = new JSONObject();
        if (ConfigTools.load(ConfigTools.CONFIG, "model").equals("dev")) {
            json.put("data", "");
        } else {
            json.put("data", "http://" + UpdateIp.nas_ip);
        }
        json.put("code", 0);
        return json.toJSONString();
    }

    @RequestMapping(value = "/nas/music/web/image.do", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getImage(String fileName, String type) {
        JSONObject json = new JSONObject();
        json.put("fileName", fileName);
        if (StringUtils.isEmpty(type)) {
            json.put("type", "file");
        } else {
            json.put("type", type);
        }
        return getImage(json);
    }

    @RequestMapping(value = "/nas/music/image.do", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getImage(@RequestBody JSONObject body) {
        String md5 = body.getString("fileName");

        File file = musicTools.getMusicOfMd5(md5, false);
        if (file.exists()) {
            try {
                return musicTools.readImage(file.getAbsolutePath());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @RequestMapping("/nas/music/random.do")
    @ResponseBody
    public String random() {
        List<MusicData> list = musicTools.getMusicList(true);
        MusicData data = list.get(Tools.randomCommon(0, list.size() - 1, 1)[0]);
        JSONObject json = new JSONObject();
        json.put("code", 0);
        json.put("data", data.getMd5());
        return json.toJSONString();
    }


    @RequestMapping("/nas/music/play.do")
    public ResponseEntity<FileSystemResource> play(String filePath, String random) {
        boolean _random;
        _random = !StringUtils.isEmpty(random) && "true".equals(random);
        if (_random) {
            List<MusicData> list = musicTools.getMusicList(true);
            MusicData data = list.get(Tools.randomCommon(0, list.size() - 1, 1)[0]);
            filePath = data.getMd5();
        }

        File file = musicTools.getMusicOfMd5(filePath, false);
        if (file.exists()) {
            return Tools.getFile(file);
        } else {
            return null;
        }
    }

    @RequestMapping("/nas/music/share.do")
    @ResponseBody
    public JSONObject share(@RequestBody JSONObject data) {
        System.out.println(data);
        String md5 = data.getString("file");
        boolean isDir = data.getBoolean("isDir");
        JSONObject json = new JSONObject();
        File music;
        if (isDir) {
            music = new File(md5);
        } else {
            music = musicTools.getMusicOfMd5(md5, false);
        }
        if (music.exists()) {
            String key = Tools.getMD5(UUID.randomUUID() + music.getAbsolutePath());
            RedisTools.set(key, music.getAbsolutePath(), 3600);
            JSONObject item = new JSONObject();
            item.put("share", key);
            json.put("code", 1);
            json.put("msg", "ok");
            json.put("data", item);
        } else {
            json.put("code", -1);
            json.put("msg", "文件不存在");
            json.put("data", "{}");
        }
        return json;
    }

    @RequestMapping("/nas/music/playShare.do")
    @ResponseBody
    public JSONObject playShare(String token) {
        JSONObject json = new JSONObject();
        String redis = RedisTools.get(token);
        if (redis != null && !"-999".equals(token)) {
            File file = new File(redis);
            JSONArray array = new JSONArray();
            if (file.isFile()) {
                array.add(musicTools.getMusicData(file.getAbsolutePath(), true));
            } else {
                for (File listFile : Objects.requireNonNull(file.listFiles())) {
                    MusicData data=musicTools.getMusicData(listFile.getAbsolutePath(), true);
                    if(data!=null) {
                        array.add(data);
                    }
                }
            }
            JSONObject item = new JSONObject();
            item.put("file", array);
            json.put("code", 0);
            json.put("data", item);
        } else {
            json.put("code", -1);
            json.put("msg", "分享已过期");
        }
        return json;
    }

}
