//
//  PhotoCollectionViewAdapter.swift
//  MCPlus
//
//  Created by seo ha on 07/02/2019.
//  Copyright © 2019 KangSH. All rights reserved.
//

import Foundation
import UIKit

class PhotoCollectionViewAdapter: NSObject {
    var list:[(String,[Photo])]?
    //체크 확인용
    var selectedArr = Set<IndexPath>()
    
    var columnCount:CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 6 : 3
}

extension PhotoCollectionViewAdapter:UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UINavigationControllerDelegate{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return list?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //리스트에서 키값을 얻어온다
        guard let list = list else{ return 0 }
        return list[section].1.count
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        //타이틀 뷰의 생성
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "PhotoCollectionViewReusableView", for: indexPath) as! PhotoCollectionViewReusableView
        guard let list = list else{ return view }
        
        let key = list[indexPath.first ?? 0].0
        
        //키값을 새탕
        view.title.text = key

        return view
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //앨범 이미지 셀을 생성
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PhotoCollectionViewCell
        guard let list = list else{ return cell }
        
        //해당 키값의 파일정보를 얻어 이미지를 불러온다
        guard let path = list[indexPath.first ?? 0].1[indexPath.row].file, let image = getImage(path: path) else{
            return cell
        }
        if list[indexPath.first ?? 0].1[indexPath.row].isSended == true{
            cell.album.borderWidth = 3.0
        }else{
            cell.album.borderWidth = 0
        }
        cell.album.image = image
        
        //체크가 되었을 경우 표시를 다르게 한다
        if self.selectedArr.contains(indexPath){
            cell.check.isChecked = true
        }else{
            cell.check.isChecked = false
        }

        //길게 누를 경우 이벤트
        cell.addLongPressGestureRecognizer { [weak self] in
            guard let `self` = self else{ return }
            let app = UIApplication.shared.delegate as! AppDelegate
            guard let nav = app.visibleViewController?.navigationController as? UINavigationController else{ return }
            
//            let alert = UIAlertController(title: "선택", message: "", preferredStyle: .actionSheet)
            
            //개별 앨범 이미지를 삭제한다
//            alert.addAction(UIAlertAction(title: "삭제", style: .destructive){ [weak collectionView](action) in
//                do {
//                    let photos = list[indexPath.first ?? 0].1
//                    let photo = photos[indexPath.row]
//                    if let file = photo.file{
//                        self.fileDelete(file: file)
//                    }
//                    let _ = photo.delete()
//                    self.selectedArr = self.selectedArr.filter({$0 != indexPath})
//                    CustomCameraViewController.photoProcessCommit.value = nil
//                }
//
//            })
            
            //아이템을 재전송
//            alert.addAction(UIAlertAction(title: "재전송", style: .destructive){ [weak collectionView](action) in
//                do {
//                    let photos = list[indexPath.first ?? 0].1
//                    let photo = photos[indexPath.row]
//                    PhotoViewController.reUploadItem.value = photo
//                    CustomCameraViewController.photoProcessCommit.value = nil
//                }
//                
//            })
            
            //디테일 보기 화면으로 이동한다
//            alert.addAction(UIAlertAction(title: "크게보기", style: .default){ (action) in
//                let storyBoard = UIStoryboard(name: "Main", bundle: nil)
//                let VC = storyBoard.instantiateViewController(withIdentifier: "PhotoDetailViewController") as! PhotoDetailViewController
//                VC.image = image
//                do {
//                    let photos = list[indexPath.first ?? 0].1
//                    let photo = photos[indexPath.row]
//                    VC.photo = photo
//                    VC.callBack = { [weak collectionView] in
//                        collectionView?.reloadData()
//                    }
//                }
//
//                nav.pushViewController(VC, animated: true)
//            })
            
            // show action sheet
//            if let popoverController = alert.popoverPresentationController {
//                popoverController.sourceView = nav.visibleViewController?.view
//                popoverController.sourceRect = CGRect(x: nav.visibleViewController?.view.bounds.midX ?? 0, y: nav.visibleViewController?.view.bounds.midY ?? 0, width: 0, height: 0)
//                popoverController.permittedArrowDirections = []
//            }
            
//            nav.visibleViewController?.present(alert, animated: true, completion: nil)
            
            let storyBoard = UIStoryboard(name: "Main", bundle: nil)
            let VC = storyBoard.instantiateViewController(withIdentifier: "PhotoDetailViewController") as! PhotoDetailViewController
            VC.image = image
            do {
                let photos = list[indexPath.first ?? 0].1
                let photo = photos[indexPath.row]
                VC.photo = photo
                VC.callBack = { [weak collectionView] in
                    collectionView?.reloadData()
                }
            }
            
            nav.pushViewController(VC, animated: true)
            
        }
        
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //체크된 인덱스가 존재하는지 여부
        let isSelected = self.selectedArr.filter({$0 == indexPath}).count > 0
        //존재할경우 해당 아이템을 제거후 반환
        if isSelected{
            self.selectedArr = self.selectedArr.filter({$0 != indexPath})
        }else{
            self.selectedArr.insert(indexPath)
        }
        collectionView.reloadItems(at: [indexPath])
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        //콜렉션뷰의 사이즈를 제어한다
        let width = collectionView.frame.width
        return CGSize(width: width/columnCount - 1, height: width/columnCount - 1)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 1.0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1.0
    }
    
    func getImage(path:String) -> UIImage? {
        //도큐먼트의 유저 디렉토리를 찾는다
        if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            //썸네일 이미지 찾기
            let thumb = dir.appendingPathComponent("thumb/\(path)")
            if let data = try? Data(contentsOf: thumb){
                return UIImage(data: data)
            }
        }
        return nil
    }
    
    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)
        }
    }
    
}
