//
//  SHInputViewModel.swift
//  ShorthandMaster
//
//  Created by 张哲 on 2020/9/24.
//  Copyright © 2020 明津李. All rights reserved.
//

import UIKit

class SHInputViewModel: NSObject {
    
    // MARK: - property
    
    
    // MARK: - func
    // MARK: 标题文字样式
    func titleAttributes() -> NSDictionary
    {
        let paragraphStyle : NSMutableParagraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.lineSpacing = 5;
        
        let titleAttributes = NSMutableDictionary.init()
        titleAttributes.setValue(UIFont.init(name: SHPingFangMedium, size: 18), forKey: NSAttributedString.Key.font.rawValue)
        titleAttributes.setValue(paragraphStyle, forKey: NSAttributedString.Key.paragraphStyle.rawValue)
        titleAttributes.setValue(UIColor.init(r: 34, g: 34, b: 34), forKey: NSAttributedString.Key.foregroundColor.rawValue)
        
        return titleAttributes
    }
    
    // MARK: 内容文字样式
    func contentAttributes() -> NSDictionary
    {
        let paragraphStyle : NSMutableParagraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.lineSpacing = 5;
        
        let titleAttributes = NSMutableDictionary.init()
        titleAttributes.setValue(UIFont.init(name: SHPingFangRegular, size: 18), forKey: NSAttributedString.Key.font.rawValue)
        titleAttributes.setValue(paragraphStyle, forKey: NSAttributedString.Key.paragraphStyle.rawValue)
        titleAttributes.setValue(UIColor.init(r: 34, g: 34, b: 34), forKey: NSAttributedString.Key.foregroundColor.rawValue)
        
        return titleAttributes
    }
    
    // MARK: 沙盒文件夹路径, 生成沙盒文件, 图片和录音都保存在这个路径下
    lazy var documentFilePath : String = {
        
        let dateFormat = Date().format("yyyyMMdd")
        let time = Date.init().timeStamp
        
        let filePath = "/" + dateFormat + time
        
        if !FileManager.default.fileExists(atPath: DocumentPath + filePath)
        {
            do
            {
                try FileManager.default.createDirectory(atPath: DocumentPath + filePath, withIntermediateDirectories: true, attributes: nil)
            }
            catch let error
            {
                print(error)
            }
        }
        
        return filePath
        
    }()

    // MARK: 获取textView中的图片, 保存到本地, 并生成数组
    func setUpImageArrayWithTextView(textView: UITextView) -> (imagesPathArray: Array<String>, imagesIndexArray: Array<Int>)
    {
        /// 图片路径数组
        var imagesPathArray = Array<String>()
        /// 图片位置数组
        var imagesIndexArray = Array<Int>()
        
//        // 创建文件夹
//        /// 文件夹路径
//        let dateFormat = Date().format("yyyyMMdd")
//        let time = Date.init().timeStamp
//        let filePath = DocumentPath + "/" + dateFormat + time
//        do
//        {
//            try FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: true, attributes: nil)
//        }
//        catch let error
//        {
//            print(error)
//
//            return (imagesPathArray, imagesIndexArray)
//        }
        
        
        // 遍历textView文字中的NSTextAttachment
        let attributedString = textView.attributedText
        
        attributedString?.enumerateAttribute(NSAttributedString.Key.attachment, in: NSRange(location: 0, length: attributedString!.length), options: NSAttributedString.EnumerationOptions.longestEffectiveRangeNotRequired, using: { (attributes, range, stop) in
                        
            if attributes != nil
            {
                let imageAttachment = attributes as! NSTextAttachment
                
                // 找到图片
                if imageAttachment.image != nil
                {
                    if (imageAttachment.image?.size.width)! > 0 && (imageAttachment.image?.size.height)! > 0
                    {
                        // 将图片保存在本地
                        
                        // 把图片转成Data类型
                        let imageData : Data = (imageAttachment.image?.jpegData(compressionQuality: 1.0))!
                        
                        // 保存的本地路径
                        let imagePath = self.documentFilePath + "/image" + imagesPathArray.count.string + ".jpeg"
                        
                        let imageUrl : URL = URL(fileURLWithPath: DocumentPath + imagePath)
                        
                        var saveSucceed : Bool = Bool(true)
                        
                        // 将图片保存到沙盒
                        do
                        {
                            try imageData.write(to: imageUrl)
                        }
                        catch let error
                        {
                            saveSucceed = false
                            print(error)
                        }
                        
                        if saveSucceed
                        {
                            // 保存成功后存储保存的路径
                            imagesPathArray.append(imagePath)
                            
                            // 存储图片位置
                            imagesIndexArray.append(range.location)
                        }
                    }
                }
            }
            
        })
        
        return (imagesPathArray, imagesIndexArray)
    }
    
    // MARK: 编辑状态下进入页面时, 把SHRecordModel类型数据转成NSMutableAttributedString
    func getAttributedStringWithSHRecordModel(recordModel: SHRecordModel) -> NSAttributedString
    {
        let attributeString : NSMutableAttributedString = NSMutableAttributedString()

        let titleString = NSAttributedString(string: recordModel.rename, attributes: (self.titleAttributes() as! [NSAttributedString.Key : Any]))
        attributeString.append(titleString)

        let contentString = NSAttributedString(string: recordModel.txt, attributes: self.contentAttributes() as? [NSAttributedString.Key : Any])
        attributeString.append(contentString)

        let imagesPath : Array = recordModel.imagesPath
        let imagesIndex : Array = recordModel.imagesIndex
        
        var i = 0
        
        for imagePath : String in imagesPath
        {
            let image : UIImage = UIImage(contentsOfFile: DocumentPath + imagePath) ?? UIImage()
            
            // 调整图片大小, 宽相同, 高随比例变化
            let newWidth = kScreenWidth - 20 * 2
            let newHeight = newWidth * image.size.height / image.size.width
            let newSize = CGSize(width: newWidth, height: newHeight)

            let imageLocation : Int = imagesIndex[i]


            let attachment = NSTextAttachment.init()
            attachment.image = image
            attachment.bounds = CGRect(origin: CGPoint.zero, size: newSize)
            let imageString = NSMutableAttributedString(attachment: attachment)

            // 设置图片文字属性
            imageString.addAttributes((self.contentAttributes() as? [NSAttributedString.Key : Any])!, range: NSRange(location: 0, length: imageString.length))
            // 设置图片间距
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 18
            imageString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: imageString.length))

            attributeString.insert(imageString, at: imageLocation)
            
            i += 1
        }
        
        return attributeString
    }
    
    // MARK: 秒数转00:00:00格式
    func getTimeStringWithSeconds(seconds : NSInteger) -> String
    {
        let hour = seconds / 60 / 60
        let minute = (seconds - hour * 60 * 60) / 60
        let second = seconds - hour * 60 * 60 - minute * 60
        
        return String(format: "%02d:%02d:%02d", hour, minute, second)
    }
}
