package com.bomostory.sceneeditmodule.view

import android.content.Context
import android.graphics.drawable.Drawable
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.view.ViewGroup
import com.bomostory.sceneeditmodule.basicdata.Scene
import kotlin.math.pow

class MovieView : ConstraintLayout {

    private var backgroundView = LayerView(context)

    var scene: Scene? = null
        set(value) {
            field = value
            value?.let {
                removeAllViews()

                backgroundView.apply {
                    layoutParams = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                    background = Drawable.createFromPath(it.backgroundPath)
                }
                addView(backgroundView)

                for (layer in it.layers) {
                    val layerView = LayerView(context)
                    layerView.apply {
                        id = layer.id
                        actors = layer.actors
                    }
                    addView(layerView)
                }
            }
        }

    var x: Int = 0
        set(value) {
            field = value
            scene?.let {

                backgroundView.apply {
                    layout(
                            (value / 2f.pow(5)).toInt(),
                            y.toInt(),
                            (value / 2f.pow(5)).toInt() + width,
                            y.toInt() + height
                    )
                }

                for (layer in it.layers) {
                    val layerView = findViewById<LayerView>(layer.id)
                    layerView.apply {
                        layout(
                                value / ((2f.pow(it.layers.indexOf(layer))).toInt()),
                                y.toInt(),
                                value / ((2f.pow(it.layers.indexOf(layer))).toInt()) + width,
                                y.toInt() + height
                        )
                    }
                }
            }
        }

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)

}