package com.lemonhc.mplus.mcare_plus.activity

import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Environment
import androidx.core.app.ActivityCompat
import android.view.View
import android.view.WindowManager
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.lemonhc.mplus.adapter.PhotoListViewAdapter
import com.lemonhc.mplus.framework.util.kotlinExtension.isCaptureFlag
import com.lemonhc.mplus.mcare_plus.R
import com.lemonhc.mplus.mcare_plus.activity.PhotoActivity.Companion.user
import com.lemonhc.mplus.model.Photo
import java.io.File

class GallaryActivity: AppCompatActivity() {
    companion object {
        var reloadTable = MutableLiveData<Boolean>()
    }

    open var photoPath = "${Environment.getExternalStorageDirectory()}/kunkuk"
    open var thumbPath = "${Environment.getExternalStorageDirectory()}/kunkuk/thumb"
    open val cameraReturnCode = 2000

    lateinit var cl_select: ConstraintLayout
    lateinit var cl_user: ConstraintLayout
    lateinit var iv_check: ImageView
    lateinit var tv_check: TextView
    lateinit var iv_user: ImageView
    lateinit var tv_user: TextView
    lateinit var bt_camera: ImageButton
    lateinit var bt_send: ImageButton
    lateinit var bt_delete: ImageButton
//    lateinit var bt_finish: ImageButton
    lateinit var listView: ListView
    lateinit var adapter: PhotoListViewAdapter

    //환자번호
    private lateinit var bt_patientId: Button
    //환자이름
    private lateinit var bt_patientNm: Button
    //환자나이/성별
    private lateinit var bt_ageGender: Button

    private lateinit var imageButton: ImageButton

    private lateinit var bt_deptNm: Button
    private lateinit var bt_treatClsKr: Button
    private lateinit var bt_doctorNm: Button

    var patientId = MutableLiveData<String>()
    var patientNm = MutableLiveData<String>()
    var ageGender = MutableLiveData<String>()
    var deptNm = MutableLiveData<String>()
    var treatClsKr = MutableLiveData<String>()
    var doctorNm = MutableLiveData<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (!isCaptureFlag) {
            window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
        }

        setContentView(R.layout.activity_gallary).run {
            cl_select = findViewById(R.id.cl_select)
            cl_user = findViewById(R.id.cl_user)
            iv_check = findViewById(R.id.iv_check)
            tv_check = findViewById(R.id.tv_check)
            iv_user = findViewById(R.id.iv_user)
            tv_user = findViewById(R.id.tv_user)
            bt_camera = findViewById(R.id.bt_camera)
            bt_send = findViewById(R.id.bt_send)
            bt_delete = findViewById(R.id.bt_delete)
//            bt_finish = findViewById(R.id.bt_finish)
            listView = findViewById(R.id.listView)
            bt_patientId = findViewById(R.id.patientId)
            bt_patientNm = findViewById(R.id.patientNm)
            bt_ageGender = findViewById(R.id.agegender)
            imageButton = findViewById(R.id.imageButton)

            bt_deptNm = findViewById(R.id.deptNm)
            bt_treatClsKr = findViewById(R.id.treatClsKr)
            bt_doctorNm = findViewById(R.id.doctorNm)
        }

        run {
            cl_select.setOnClickListener(allSelectClicked())
            cl_user.setOnClickListener(allUserClicked())
            bt_camera.setOnClickListener(cameraClicked())
            bt_send.setOnClickListener(sendClicked())
            bt_delete.setOnClickListener(deleteClicked())
//            bt_finish.setOnClickListener(finishClicked())
            imageButton.setOnClickListener(finishClicked())
        }

        run {
            patientId.observe(this, Observer {
                bt_patientId.text = it
            })
            patientNm.observe(this, Observer {
                bt_patientNm.text = it
            })
            ageGender.observe(this, Observer {
                bt_ageGender.text = it
            })
            deptNm.observe(this, Observer {
                bt_deptNm.text = it
            })
            treatClsKr.observe(this, Observer {
                bt_treatClsKr.text = it
            })
            doctorNm.observe(this, Observer {
                bt_doctorNm.text = it
            })
        }

        val photos: List<Pair<String, MutableList<Photo>>> = Photo.list(user, this)

        adapter = PhotoListViewAdapter(this)
        adapter.items = photos
        listView.adapter = adapter

        patientId.value = user.patientId
        patientNm.value = user.patientNm
        ageGender.value = "${user.age} / ${user.gender}"

        deptNm.value = user.deptNm
        treatClsKr.value = user.treatClsKr
        doctorNm.value = user.doctorNm

        reloadTable.observe(this, Observer {
            this.reload()
        })
    }

    private fun reload() {
        when(adapter.allPatientFlag) {
            true -> {
                val photos: List<Pair<String, MutableList<Photo>>> = Photo.allList(user, this)
                adapter = listView.adapter as PhotoListViewAdapter
                adapter.items = photos
            }
            false -> {
                val photos: List<Pair<String, MutableList<Photo>>> = Photo.list(user, this)
                adapter = listView.adapter as PhotoListViewAdapter
                adapter.items = photos
            }
        }
        adapter.notifyDataSetChanged()
    }

}

fun GallaryActivity.allSelectClicked(): View.OnClickListener {
    return View.OnClickListener {
        if (!adapter.checkFlag) {
            adapter.checkFlag = true
            iv_check.setImageResource(R.drawable.chk_active)
        } else {
            adapter.checkFlag = false
            iv_check.setImageResource(R.drawable.chk_default)
        }
        adapter.allCheck()
    }
}

fun GallaryActivity.allUserClicked(): View.OnClickListener {
    return View.OnClickListener {
        /* 전체선택 후 전체환자를 클릭하면 모두 초기화 */
        adapter.checkFlag = false
        iv_check.setImageResource(R.drawable.chk_default)
        adapter.allCheck()
        if (!adapter.allPatientFlag) {
            adapter.allPatientFlag = true
            iv_user.setImageResource(R.drawable.chk_active)
            val photos: List<Pair<String, MutableList<Photo>>> = Photo.allList(user, this)
            adapter = listView.adapter as PhotoListViewAdapter
            adapter.items = photos
        } else {
            adapter.allPatientFlag = false
            iv_user.setImageResource(R.drawable.chk_default)
            val photos: List<Pair<String, MutableList<Photo>>> = Photo.list(user, this)
            adapter = listView.adapter as PhotoListViewAdapter
            adapter.items = photos
        }
        adapter.notifyDataSetChanged()
    }
}

fun GallaryActivity.cameraClicked(): View.OnClickListener {
    return View.OnClickListener {
        if (checkPermissionCamera()) {
            val directory = File(this.photoPath)
            if (!directory.exists()) {
                directory.mkdirs()
            }

            //미디어스캐닝 방지
            val nomedia = File("${this.photoPath}/.nomedia")
            if (!nomedia.exists()) {
                nomedia.mkdir()
            }

            val intent = Intent(this, CameraActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
            startActivity(intent)
            this.finish()
        }
    }
}

fun GallaryActivity.sendClicked(): View.OnClickListener {
    return View.OnClickListener {
        if (adapter.checkedItems.count() == 0) {
            Toast.makeText(this, "파일을 한 개 이상 선택해주세요", Toast.LENGTH_LONG).show()
        } else {
            adapter.sendItem()
            /* 전체선택 후 파일 업로드를 누르면 초기화 */
            adapter.checkFlag = false
            iv_check.setImageResource(R.drawable.chk_default)
            adapter.allCheck()
        }
    }
}

fun GallaryActivity.deleteClicked(): View.OnClickListener {
    return View.OnClickListener {
        if (adapter.checkedItems.count() == 0) {
            Toast.makeText(this, "파일을 한 개 이상 선택해주세요", Toast.LENGTH_LONG).show()
        } else {
            AlertDialog.Builder(this)
                    .setTitle("정말 삭제하시겠습니까?")
                    .setMessage("")
                    .setPositiveButton(android.R.string.ok) { _, _ ->
                        adapter.deleteItem()
                    }
                    .setNegativeButton(android.R.string.cancel) { _, _ ->
                    }
                    .setCancelable(true)
                    .create()
                    .show()
        }
    }
}

fun GallaryActivity.finishClicked(): View.OnClickListener {
    return View.OnClickListener {
        this.finish()
    }
}

/**
 * 카메라 퍼미션 확인
 */
fun GallaryActivity.checkPermissionCamera(): Boolean {
    val chkPerStorage: Boolean = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
    val chkPerCameara: Boolean = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
    if (chkPerStorage || chkPerCameara) {
        val shoPerStorage:Boolean = ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        val shoPerCamera:Boolean = ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
        if (shoPerStorage && shoPerCamera) { // 사용자 권한 취소로 인한 권한 재요청
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA), this.cameraReturnCode)
        } else { // 최초로 권한을 요청
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA), this.cameraReturnCode)
        }
        return false
    } else {
        return true
    }
}
