//
//  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 cancelButton: UIButton!{
        didSet{
            cancelButton.addTapGestureRecognizer(action: self.cancelAction)
        }
    }
    
    @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 successCount = 0
    var failCount = 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()
            }
        }
        
        PhotoViewController.reUploadItem.signal.observe { [weak self](item) in
            guard let value = item.value as? Photo else{ return }
            self?.uploadItem(value)
        }
        
    }
    
    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(){
        successCount = 0
        failCount = 0
        guard self.adapter.selectedArr.count > 0 else{
            self.showAlert("파일을 한 개 이상 선택해주세요", "", "확인")
            return
        }
        //비동기화 통신코드 동기화 구현 필요
        for indexPath in self.adapter.selectedArr{
            guard let list = self.list.value else{ return }
            
            let photos = list[indexPath.first ?? 0].1
            let photo = photos[indexPath.row]
            //선택된 사진이 이미 보낸적이 있다면 업데이트하지 않는다
            if photo.isSended == false{
                self.uploadItem(photo)
            }
            self.adapter.selectedArr = self.adapter.selectedArr.filter({$0 != indexPath})
        }
        
        if let parent = self.parent as? PictureViewController{
            parent.callBack?(["success":"\(successCount)", "fail":"\(failCount)"])
        }
        self.showAlert("서버에 업로드 되었습니다.", "", "확인")
    }
    
    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()
                }else{
                    self?.failCount += 1
                }
            }
        
    }
    
    //선택된 사진 삭제
    func deleteAction(){
        guard self.adapter.selectedArr.count > 0 else{
            self.showAlert("파일을 한 개 이상 선택해주세요", "", "확인")
            return
        }
        
        self.showAlert("정말 삭제하시겠습니까?", "", "확인", "취소", { [weak self] (action) in
            guard let `self` = self else{ return }
            for indexPath in self.adapter.selectedArr{
                guard let list = self.list.value else{ return }
                
                let photos = list[indexPath.first ?? 0].1
                let photo = photos[indexPath.row]
                do {
                    if let file = photo.file{
                        self.fileDelete(file: file)
                    }
                    
                    let _ = photo.delete()
                }
                self.adapter.selectedArr = self.adapter.selectedArr.filter({$0 != indexPath})
            }
            
            self.reloadTable()
            }, { [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.allUserAlbumLabel.text == "전체환자"{
            self.list.value = Photo.list(user: user)
        }else{
            self.list.value = Photo.allList(user: user)
        }
    }
    
    //커스텀 카메라 호출
    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
            
            for i in 0..<section{
                let row = self.photoCollectionView.numberOfItems(inSection: i)
                for j in 0..<row{
                    selectedArr.insert(IndexPath(row: j, section: i))
                }
            }
        }else{
            self.allSelectLabel.text = "전체선택"
            self.allSelectCheck.isChecked = false
        }
        
        self.adapter.selectedArr = selectedArr
        self.photoCollectionView.reloadData()
    }
    
    //전체앨범 or 선택환자
    func allUserAlbumAction(){
        if self.allUserAlbumLabel.text == "전체환자"{
            self.allUserAlbumLabel.text = "개인환자"
            self.allUserAlbumCheck.isChecked = true
            
        }else{
            self.allUserAlbumLabel.text = "전체환자"
            self.allUserAlbumCheck.isChecked = false
        }
        
        self.reloadTable()
        
    }
    
    
}



