package com.bomostory.sceneeditmodule.basicdata

import android.content.ContentResolver
import android.media.MediaMetadataRetriever
import android.os.Environment
import android.provider.MediaStore
import org.json.JSONObject
import java.io.File

object DataParser {

    fun parseMusicSource(contentResolver: ContentResolver,libraryPaths:List<String>):MusicSource{
        val musicSource = MusicSource()
        musicSource.library = parseMusic(libraryPaths)
        musicSource.device = parseMusic(contentResolver,libraryPaths)
        return musicSource
    }

    private fun parseMusic(paths: List<String>): ArrayList<Music> {
        val mediaMetadataRetriever = MediaMetadataRetriever()
        val musics = ArrayList<Music>()

        for (path in paths) {
            val file = File(path)
            mediaMetadataRetriever.setDataSource(path)

            val music = Music()
            music.name = file.name
            music.path = path
            music.duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION).toLong()
            musics.add(music)
        }
        return musics
    }

    private fun parseMusic(contentResolver: ContentResolver,paths: List<String>): ArrayList<Music>{
        val selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"
        val projection = arrayOf(
                MediaStore.Audio.Media.TITLE,
                MediaStore.Audio.Media.DATA,
                MediaStore.Audio.Media.DURATION
        )
        val cursor = contentResolver.query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                projection,
                selection,
                null, null
        )

        val musics = ArrayList<Music>()
        while (cursor.moveToNext()) {
            val music = Music()
            music.name = cursor.getString(0)
            music.path = cursor.getString(1)
            music.duration = cursor.getString(2).toLong()
            val file = File(music.path)
            if (!paths.contains(file.path)) {
                musics.add(music)
            }
        }
        return musics
    }

    fun parseStory(arrayList: ArrayList<JSONObject>): Story {
        val story = Story()
        for (jsonObject in arrayList) {
            val scene = parseScene(jsonObject)
            story.scenes.add(scene)
        }
        return story
    }

    private fun parseScene(jsonObject: JSONObject): Scene {
        val scene = Scene()

        val layer0 = parseLayer(JSONObject(jsonObject.optString("layer0")))
        val layer1 = parseLayer(JSONObject(jsonObject.optString("layer1")))
        val layer2 = parseLayer(JSONObject(jsonObject.optString("layer2")))
        val layer3 = parseLayer(JSONObject(jsonObject.optString("layer3")))
        val layer4 = parseLayer(JSONObject(jsonObject.optString("layer4")))

        scene.layers.add(layer0)
        scene.layers.add(layer1)
        scene.layers.add(layer2)
        scene.layers.add(layer3)
        scene.layers.add(layer4)

        scene.record = parseRecord(jsonObject.optJSONObject("record"))

        scene.backgroundPath = (Environment.getExternalStorageDirectory().toString()
                + "/Android/yuheng/" + jsonObject.optString("background"))

        return scene
    }

    private fun parseRecord(jsonObject: JSONObject): Record {
        val record = Record()
        record.period = jsonObject.optLong("period")
        val tracks = jsonObject.optJSONArray("tracks")
        tracks?.let {
            for (i in 0 until it.length()) {
                val track = parseTrack(tracks.optJSONObject(i))
                record.tracks.add(track)
            }
        }
        return record
    }

    private fun parseTrack(jsonObject: JSONObject): Track {
        val track = Track()
        track.time = jsonObject.optLong("time")
        track.positionX = jsonObject.optInt("positionX")
        return track
    }

    private fun parseLayer(jsonObject: JSONObject): Layer {
        val layer = Layer()
        layer.id = jsonObject.optInt("id")
        layer.name = jsonObject.optString("name")
        val actors = jsonObject.optJSONArray("actor")
        for (i in 0 until actors.length()) {
            val actor = parseActor(actors.optJSONObject(i))
            layer.actors.add(actor)
        }
        return layer
    }

    private fun parseActor(jsonObject: JSONObject): Actor {
        val actor = Actor()
        actor.resourcePath = (Environment.getExternalStorageDirectory().toString()
                + "/Android/yuheng/" + jsonObject.optString("resource"))
        actor.positionX = jsonObject.optInt("positionX")
        actor.positionY = jsonObject.optInt("positionY")
        actor.sideLength = jsonObject.optInt("size")
        return actor
    }

}