package com.yutou.nas.Controllers;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yutou.nas.mybatis.model.MusicData;
import com.yutou.nas.utils.ConfigTools;
import com.yutou.nas.utils.MusicToolsServiceImpl;
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.util.StringUtils;
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.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.List;

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

@Controller
@RequestMapping("/nas/music/")
public class MusicController {

    @Resource
    MusicToolsServiceImpl musicTools;

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

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

        //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", JSONArray.toJSON(musicTools.getPath(path, type)));
        return json.toJSONString();
    }

    @ResponseBody
    @RequestMapping("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", JSONArray.toJSON(musicTools.getAllAlbum()));
        } else {
            json.put("data", JSONArray.toJSON(musicTools.selectAlbum(album)));
        }
        return json.toJSONString();
    }

    @ResponseBody
    @RequestMapping("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", JSONArray.toJSON(musicTools.getAllArtist()));
        } else {
            json.put("data", JSONArray.toJSON(musicTools.selectArtist(artist)));
        }
        return json.toJSONString();
    }

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

    @RequestMapping("find/file.do")
    @ResponseBody
    public String findFile(@RequestBody JSONObject body) {
        String path = body.getString("path");
        if (!path.startsWith(defaultMusicPath)) {
            path = Tools.base64ToString(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.getMusicData(path));
        return json.toJSONString();
    }

    @RequestMapping("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 = "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 = "image.do", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getImage(@RequestBody JSONObject body) {
        String fileName = body.getString("fileName");
        if (!fileName.startsWith(defaultMusicPath)) {
            fileName = Tools.base64ToString(fileName);
        }
        List<MusicData> list = null;
        if (body.getString("type").equals("album")) {
            list = musicTools.selectAlbum(fileName);
        }
        File file;
        if (list != null && !list.isEmpty()) {
            fileName = list.get(0).getFile();
        }
        file = new File(fileName);
        if (file.exists()) {
            try {
                return musicTools.readImage(file.getAbsolutePath());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @RequestMapping("random.do")
    @ResponseBody
    public String random() {
        List<MusicData> list = musicTools.getMusicList();
        MusicData data = list.get(Tools.randomCommon(0, list.size() - 1, 1)[0]);
        JSONObject json = new JSONObject();
        json.put("code", 0);
        try {
            json.put("data", URLEncoder.encode(getBase64(data.getFile()), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return json.toJSONString();
    }

    private String getBase64(String str) {
        return new String(Base64.getEncoder().encode(str.getBytes()));
    }


    @RequestMapping("play.do")
    public ResponseEntity<FileSystemResource> play(String filePath, String random) {
        String _filePath;
        boolean _random;
        _random = !StringUtils.isEmpty(random) && random.equals("true");
        _filePath = Tools.base64ToString(filePath);
        if (_random) {
            List<MusicData> list = musicTools.getMusicList();
            MusicData data = list.get(Tools.randomCommon(0, list.size() - 1, 1)[0]);
            _filePath = data.getFile();
        }
        File file = new File(_filePath);
        if (file.exists()) {
            return Tools.getFile(file);
        } else {
            return null;
        }
    }

}
