//
//  ViewController.swift
//  photosApp2
//
//  Created by Muskan on 10/4/17.
//  Copyright © 2017 akhil. All rights reserved.
// 갤러리뷰 화면이다.

import UIKit
import Photos
import ReactiveCocoa
import ReactiveSwift

class PhotoViewController: UIViewController{
    
    @IBOutlet weak var patientIdLabel :UILabel!{
        didSet{
            patientIdLabel.reactive.text <~ PictureViewController.patientId
        }
    }
    
    @IBOutlet weak var patientNmLabel :UILabel!{
        didSet{
            patientNmLabel.reactive.text <~ PictureViewController.patientNm
        }
    }
    
    @IBOutlet weak var ageGenderLabel :UILabel!{
        didSet{
            ageGenderLabel.reactive.text <~ PictureViewController.ageGender
        }
    }
    
    @IBOutlet weak var okButton: UIButton!{
        didSet{
            okButton.addTapGestureRecognizer(action: self.okAction)
        }
    }
    
    @IBOutlet weak var photoCollectionView: UICollectionView!{
        didSet{
            photoCollectionView.delegate = adapter
            photoCollectionView.dataSource = adapter
            self.list.signal.observe({ [weak self](item) in
                guard let value = item.value else { return }
                self?.adapter.list = value
                self?.photoCollectionView.reloadData()
                
            })
        }
    }
    
    @IBOutlet weak var allSelectButton: UIView!{
        didSet{
            allSelectButton.addTapGestureRecognizer(action: self.allSelectAction)
        }
    }
    
    @IBOutlet weak var allSelectLabel: UILabel!
    
    @IBOutlet weak var allSelectCheck: CheckImageButton!
    
    @IBOutlet weak var allUserAlbumButton: UIView!{
        didSet{
            allUserAlbumButton.addTapGestureRecognizer(action: self.allUserAlbumAction)
        }
    }
    
    @IBOutlet weak var allUserAlbumLabel: UILabel!
    
    @IBOutlet weak var allUserAlbumCheck: CheckImageButton!
    
    @IBOutlet weak var cameraButton: UIButton!{
        didSet{
            cameraButton.addTapGestureRecognizer(action: self.cameraAction)
        }
    }
    
    @IBOutlet weak var deleteButton: UIButton!{
        didSet{
            deleteButton.addTapGestureRecognizer(action: self.deleteAction)
        }
    }
    
    @IBOutlet weak var closeButton: UIImageView!{
        didSet{
            closeButton.addTapGestureRecognizer(action: self.cancelAction)
        }
    }
    
    @IBOutlet weak var deptNmLabel: UILabel!{
        didSet{
            PictureViewController.deptNm.signal.observe { [weak deptNmLabel](item) in
                guard let value = item.value as? String else{ return }
                let attr = deptNmLabel?.attributedText?.attributes(at: 0, effectiveRange: nil)
                let attrString = NSMutableAttributedString(string: value, attributes: attr)
                deptNmLabel?.attributedText = attrString
            }
        }
    }
    
    @IBOutlet weak var treatClsKrLabel: UILabel!{
        didSet{
            PictureViewController.treatClsKr.signal.observe { [weak treatClsKrLabel](item) in
                guard let value = item.value as? String else{ return }
                let attr = treatClsKrLabel?.attributedText?.attributes(at: 0, effectiveRange: nil)
                let attrString = NSMutableAttributedString(string: value, attributes: attr)
                treatClsKrLabel?.attributedText = attrString
            }
        }
    }
    
    @IBOutlet weak var doctorNmLabel: UILabel!{
        didSet{
            PictureViewController.doctorNm.signal.observe { [weak doctorNmLabel](item) in
                guard let value = item.value as? String else{ return }
                let attr = doctorNmLabel?.attributedText?.attributes(at: 0, effectiveRange: nil)
                let attrString = NSMutableAttributedString(string: value, attributes: attr)
                doctorNmLabel?.attributedText = attrString
            }
        }
    }
    
    
    let adapter = PhotoCollectionViewAdapter()
    
    var list = MutableProperty<[(String,[Photo])]?>(nil)
    
    static var reUploadItem = MutableProperty<Photo?>(nil)
    
    var allSelectCheckFlag = MutableProperty<Bool>(false)

    var successCount = 0
    var failCount = 0
    var uploadCount = 0 //전체 업로드한 개수를 기억한다.
}

extension PhotoViewController{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        PictureViewController.patientId.signal.observe { [weak self](item) in
            guard let _ = item.value else{ return }
            
            if let VC = self?.parent as? PictureViewController, let user = VC.user{
                self?.list.value = Photo.list(user: user)
            }
        }
        
        //이미지 프로세싱 완료처리
        CustomCameraViewController.photoProcessCommit.signal.observe { [weak self](item) in
            DispatchQueue.main.async {
                self?.reloadTable(checkAll: self?.allUserAlbumCheck.checked ?? false)
            }
        }
        
        PhotoViewController.reUploadItem.signal.observe { [weak self](item) in
            guard let value = item.value as? Photo else{ return }
            self?.uploadItem(value)
        }
        
        allSelectCheckFlag.signal.observe { [weak self](item) in
            guard let value = item.value as? Bool else{ return }
            guard let list = self?.adapter.list else{ return }
            for item in list{
                for item2 in item.1{
                    item2.isChecked = value
                }
            }
            self?.photoCollectionView.reloadData()
        }
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func cancelAction(){
        self.navigationController?.popViewController(animated: true)
    }
    
    //선택된 사진 전송
    func okAction(){
        self.successCount = 0
        self.failCount = 0
        self.uploadCount = 0
        
        let isCheckCount = self.adapter.list?.filter({
            $0.1.filter({$0.isChecked}).count > 0
        }).count ?? 0
        guard isCheckCount > 0 else{
//            self.showAlert("파일을 한 개 이상 선택해주세요", "", "확인")
            return
        }
        guard let list = self.adapter.list else{ return }
        var arrayUploadList:[Photo]? = [Photo]()
        
        for item in list{
            for item2 in item.1{
                //선택된 사진이 이미 보낸적이 있다면 업데이트하지 않는다
                if item2.isChecked && item2.isSended == false{
                    arrayUploadList?.append(item2)
                }else{
                    continue
                }
            }
        }
        
        self.uploadCount = arrayUploadList?.count ?? 0
        if self.uploadCount != 0 {
            for upload in arrayUploadList! {
                self.uploadItem(upload)
            }
        }
        if let parent = self.parent as? PictureViewController{
            parent.callBack?(["success":"\(successCount)", "fail":"\(failCount)"])
        }
    }
    
    func uploadItem(_ photo:Photo){
        var param = [String:Any]()
        param["hospitalCd"] = photo.user?.hospitalCD ?? ""
        param["userId"] = photo.user?.userId ?? ""
        param["patientId"] = photo.user?.patientId ?? ""
        param["deptCd"] = photo.user?.deptCd ?? ""
        param["doctorId"] = photo.user?.doctorId ?? ""
        param["searchCls"] = photo.user?.treatCls ?? ""
        param["thumbnail"] = ""
        param["excutionDtTm"] = Date().fromString(format: "yyyy-MM-dd hh:mm:ss")
        param["visitDt"] = photo.user?.visitDt ?? ""
        
        if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            //원본 이미지 찾기
            let origin = dir.appendingPathComponent("kunkuk/\(photo.file ?? "")")
            
            if let data = try? Data(contentsOf: origin){
//                let binaryString = data.reduce("") { (acc, byte) -> String in
//                    print(String(byte, radix: 2))
//                    return acc + String(byte, radix: 2)
//                }
//                param["image"] = binaryString
                param["image"] = data.base64EncodedString()
            }
        }
        
        let url = "\(MCarePlusConstants.DOMAIN_NAME)\(photo.user?.serviceUrl ?? "")"
        
        APIClient(url)
            .param(reqParam: param)
            .enType(.json)
            .connect { [weak self](result:[String:Any]) in
                print(result)
                guard let `result` = result["result"] as? [[String:Any]] else{ return }
                let returnCd = result.first?["returnCd"] as? String
                //성공일시
                if returnCd == "0000"{
                    self?.successCount += 1
                    photo.isSended = true
                    photo.update()
                    self?.reloadTable(checkAll: self?.allUserAlbumCheck.checked ?? false )
                }else{
                    self?.failCount += 1
                }
                self!.isUploadComplete()
            }
    }
    
    func isUploadComplete(){
        let total = self.uploadCount
        let sumCount = self.successCount + self.failCount
        
        if total == sumCount {
            //전송완료
            if failCount == 0 {
                self.showAlert("\(successCount)건 전송 완료되었습니다.", "", "확인")
            } else {
                self.showAlert("\(failCount)건 전송 실패하였습니다.", "", "확인")
            }
        } else {
            //전송중
        }
    }
    
    //선택된 사진 삭제
    func deleteAction(){
        let isCheckCount = self.adapter.list?.filter({
            $0.1.filter({$0.isChecked}).count > 0
        }).count ?? 0
        guard isCheckCount > 0 else{
//            self.showAlert("파일을 한 개 이상 선택해주세요", "", "확인")
            return
        }
        
        self.showAlert("정말 삭제하시겠습니까?", "", "확인", "취소", { [weak self] (action) in
            guard let `self` = self else{ return }
            guard let list = self.adapter.list else{ return }
            for item in list{
                for item2 in item.1{
                    if item2.isChecked{
                        do {
                            if let file = item2.file{
                                self.fileDelete(file: file)
                            }
                            
                            let _ = item2.delete()
                        }
                    }else{
                        continue
                    }
                }
            }
            
            self.reloadTable(checkAll: self.allUserAlbumCheck.checked)
            }, { [weak self] (action) in
                
        })
    }
    
    func fileDelete(file:String){
        //도큐먼트의 유저 디렉토리를 찾는다
        if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            let path = dir.appendingPathComponent("kunkuk")
            //해당 폴더가 없으면 생성
            if !FileManager.default.fileExists(atPath: path.path){
                try? FileManager.default.createDirectory(at: path, withIntermediateDirectories: true, attributes: nil)
            }
            
            let thumb = dir.appendingPathComponent("thumb")
            //해당 폴더가 없으면 생성
            if !FileManager.default.fileExists(atPath: thumb.path){
                try? FileManager.default.createDirectory(at: thumb, withIntermediateDirectories: true, attributes: nil)
            }
            
            let fileURL = path.appendingPathComponent(file)
            let thumbURL = thumb.appendingPathComponent(file)
            
            try? FileManager.default.removeItem(at: fileURL)
            try? FileManager.default.removeItem(at: thumbURL)
        }
    }
    
    //테이블 리로드 rx swift 이용
    func reloadTable(){
        guard let parent = self.parent as? PictureViewController else{ return }
        guard let user = parent.user else{ return }
        if self.allUserAlbumCheck.checked {
            self.list.value = Photo.list(user: user)
        }else{
            self.list.value = Photo.allList(user: user)
        }
        self.allSelectCheckFlag.value = false
        self.allUserAlbumCheck.checked = !self.allUserAlbumCheck.checked
    }
    //테이블 리로드 rx swift 이용
    func reloadTable(checkAll:Bool){
        guard let parent = self.parent as? PictureViewController else{ return }
        guard let user = parent.user else{ return }
        if checkAll {
            self.list.value = Photo.allList(user: user)
        }else{
            self.list.value = Photo.list(user: user)
        }
        self.allSelectCheckFlag.value = false
        self.allUserAlbumCheck.checked = checkAll
    }
    
    
    
    
    //커스텀 카메라 호출
    func cameraAction(){
        if let parent = self.parent as? PictureViewController{
            parent.cameraAction(action: nil)
        }
    }
    
    //전체선택 체크박스
    func allSelectAction(){
        //인덱스패스 저장용
        var selectedArr = Set<IndexPath>()
        //섹션카운트
        let section = self.photoCollectionView.numberOfSections
        
//        //전체선택일경우 전체선택 or 해제
//        if self.allSelectLabel.text == "전체선택"{
//            self.allSelectLabel.text = "선택해제"
//            self.allSelectCheck.isChecked = true
//            self.allSelectCheckFlag.value = true
//        }else{
//            self.allSelectLabel.text = "전체선택"
//            self.allSelectCheck.isChecked = false
//            self.allSelectCheckFlag.value = false
//        }
        
//        if self.allSelectCheck.isChecked {
//            self.allSelectLabel.text = "선택해제"
//        } else {
//            self.allSelectLabel.text = "전체선택"
//        }
        self.allSelectCheck.isChecked = !self.allSelectCheck.isChecked
        self.allSelectCheckFlag.value = !self.allSelectCheckFlag.value
        
    }
    
    //전체환자 체크박스
    func allUserAlbumAction(){
//        if self.allUserAlbumLabel.text == "전체환자"{
//            self.allUserAlbumLabel.text = "개인환자"
//            self.allUserAlbumCheck.isChecked = true
//
//        }else{
//            self.allUserAlbumLabel.text = "전체환자"
//            self.allUserAlbumCheck.isChecked = false
//        }
        
//        if self.allUserAlbumCheck.isChecked {
//            self.allUserAlbumLabel.text = "개인환자"
//        } else {
//            self.allUserAlbumLabel.text = "전체환자"
//        }
//        self.allUserAlbumCheck.isChecked = !self.allUserAlbumCheck.isChecked
        self.allSelectCheck.isChecked = false
        self.reloadTable()
        
    }
    
    
}



