//
//  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)
        }
    }
    
    
    
    let adapter = PhotoCollectionViewAdapter()
    
    var list = MutableProperty<[String:[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 value = item.value else{ return }
            let user = User()
            user.patientId = value
            self?.list.value = Photo.list(user: user)
        }
        
        //이미지 프로세싱 완료처리
        CustomCameraViewController.photoProcessCommit.signal.observe { [weak self](item) in
            DispatchQueue.main.async {
                self?.reloadTable()
            }
        }
    }
    
    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
        //비동기화 통신코드 동기화 구현 필요
        for indexPath in self.adapter.selectedArr{
            guard let list = self.list.value else{ return }
            let key = Array(list.keys)[indexPath.section]
            
            //선택된 사진이 이미 보낸적이 있다면 업데이트하지 않는다
            if let photo = list[key]?[indexPath.row], photo.isSended == false{
                self.uploadItem(photo)
            }
        }
        
        if let parent = self.parent as? PictureViewController{
            parent.callBack?(["success":"\(successCount)", "fail":"\(failCount)"])
        }
        self.reloadTable()
    }
    
    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["treatCls"] = photo.user?.treatCls ?? ""
        param["excutionDtTm"] = Date().fromString(format: "yyyy-MM-dd hh:mm:ss")
        
        var fileParam = [[String:Data]]()
        
        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){
                fileParam.append(["image":data])
            }
            //썸네일 이미지 찾기
            let thumb = dir.appendingPathComponent("thumb/\(photo.file ?? "")")
            if let data = try? Data(contentsOf: thumb){
                fileParam.append(["thumbnail":data])
            }
        }
        
        APIClient("\(MCarePlusConstants.DOMAIN_NAME)\(MCarePlusConstants.APP_NAME)\(Constants.WOUND_IMG_URL).json")
            .param(reqParam: param)
            .param(fileParam: fileParam)
            .connect { [weak self](result:[String:Any]) in

                //성공일시
                if result["returnCd"] as? String == "0000"{
                    self?.successCount += 1
                    photo.isSended = true
                    photo.update()
                }else{
                    self?.failCount += 1
                }
            }
        
        
        
        
    }
    
    //선택된 사진 삭제
    func deleteAction(){
        for indexPath in self.adapter.selectedArr{
            guard let list = self.list.value else{ return }
            let key = Array(list.keys)[indexPath.section]
            
            if let photo = list[key]?[indexPath.row]{
                if let file = photo.file{
                    self.fileDelete(file: file)
                }
                
                let _ = photo.delete()
            }
        }
        
        self.reloadTable()
        
    }
    
    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(){
        if self.allUserAlbumLabel.text == "전체환자"{
            if let parent = self.parent as? PictureViewController, let user = parent.user{
                self.list.value = Photo.list(user: user)
            }
            
        }else{
            self.list.value = Photo.allList()
        }
    }
    
    //커스텀 카메라 호출
    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()
        
    }
    
    
}



