import UIKit
import AVFoundation
import AVKit
import Async
import WowonderMessengerSDK
import Toast_Swift
import SDWebImage

class AddNewStoryVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var captionTextView: EmojiTextView!
    
    // MARK: - Properties
    
    var selectedImage: UIImage? = nil
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popToRootViewController(animated: true)
    }
    
    // Emoji Button Action
    @IBAction func emojiButtonAction(_ sender: UIButton) {
        self.captionTextView.isEmojiKeyboard = true
        self.captionTextView.becomeFirstResponder()
    }
    
    // Send Button Action
    @IBAction func sendButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        var imageData = Data()
        imageData = self.selectedImage?.sd_imageData() ?? Data()
        self.createStory(data: imageData, type: "image")
    }
    
    // Edit Button Action
    @IBAction func editButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.photoEditor.photoEditorVC() {
            newVC.selectedImage = self.selectedImage
            newVC.delegate = self
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.setUpCaptionTextView()
        self.setupUI()
    }
    
    // SetUp Caption TextView
    func setUpCaptionTextView() {
        self.captionTextView.delegate = self
        self.captionTextView.addPlaceholder("Add a caption...", with: .text_color)
    }
    
    // Setup UI
    func setupUI() {
        self.imageView.image = self.selectedImage
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension AddNewStoryVC {
    
    private func createStory(data: Data, type: String) {
        self.showProgressDialog(text: NSLocalizedString("Loading...", comment: "Loading..."))
        let sessionToken = AppInstance.instance.sessionId ?? ""
        let storyText = self.captionTextView.text ?? ""
        Async.background {
            StoriesManager.instance.createStory(session_Token: sessionToken, type: type, storyDescription: storyText, storyTitle: "", data: data, completionBlock: { (success, sessionError, serverError, error) in
                Async.main {
                    self.dismissProgressDialog {
                        if success != nil {
                            print("userList = \(success?.apiStatus ?? 0)")
                            self.navigationController?.popToRootViewController(animated: true)
                        } else if sessionError != nil {
                            self.view.makeToast(sessionError?.errors?.error_text)
                            print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                        } else if serverError != nil {
                            self.view.makeToast(serverError?.errors?.error_text)
                            print("serverError = \(serverError?.errors?.error_text ?? "")")
                        } else {
                            self.view.makeToast(error?.localizedDescription)
                            print("error = \(error?.localizedDescription ?? "")")
                        }
                    }
                }
            })
        }
    }
    
}

// MARK: UITextViewDelegate Methods
extension AddNewStoryVC: UITextViewDelegate {
    
    func textViewDidEndEditing(_ textView: UITextView) {
        self.captionTextView.isEmojiKeyboard = false
    }
    
}

// MARK: PhotoEditorVCDelegate
extension AddNewStoryVC: PhotoEditorVCDelegate {
    
    func handlePhotoEditorSaveButtonTap(image: UIImage) {
        self.selectedImage = image
        self.setupUI()
    }
    
}
