//
//  ViewController.swift
//  writeas
//
//  Created by Matt Baer on 12/29/15.
//  Copyright © 2015 A Bunch Tell. All rights reserved.
//

import Cocoa

class ViewController: NSViewController, NSTextViewDelegate, NSUserNotificationCenterDelegate {

    @IBOutlet var writerText: NSTextView!

    let draftFile = "\(NSHomeDirectory())/.writeas/draft.txt"

    override func viewDidLoad() {
        super.viewDidLoad()

        loadDocument()

        writerText.font = NSFont(name: "Lora", size: Preferences.getFontSize())
        writerText.isHorizontallyResizable = false
        writerText.textContainerInset = NSSize(width: 16, height: 16)
        writerText.isAutomaticQuoteSubstitutionEnabled = false
        writerText.isAutomaticDashSubstitutionEnabled = false

        NSUserNotificationCenter.default.delegate = self

        // Do any additional setup after loading the view.
        writerText.delegate = self
    }

    override func viewDidAppear() {
        super.viewDidAppear()

        configureWindow()

        // Style the window
        self.view.window!.title = "Write.as"
        self.view.window!.titlebarAppearsTransparent = true
        self.view.window!.isMovableByWindowBackground = true
        self.view.window!.titleVisibility = .hidden
        self.view.window!.backgroundColor = NSColor.white
    }

    func configureWindow() {
        // Fit textview to window size
        writerText.setFrameSize(NSSize(width: self.view.window!.frame.width, height: self.view.window!.frame.height))
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    fileprivate func getDraftPath() -> URL? {
        return URL(fileURLWithPath: draftFile)
    }

    func saveDocument() {
        // Save whatever's written
        let path = getDraftPath()
        if path == nil {
            return
        }

        //writing
        do {
            try writerText.textStorage!.string.write(to: path!, atomically: false, encoding: .utf8)
        } catch (let err) {
            print("ERROR writing: \(err)")
        }
    }

    func loadDocument() {
        let path = getDraftPath()
        if path == nil {
            return
        }
        do {
            let draftText = try String(contentsOf: path!, encoding: .utf8)
            writerText.string = draftText
        } catch (let err) {
            print("ERROR loading: \(err)")
        }
    }

    func publish() {
        saveDocument()

        DispatchQueue.global(qos: .background).async {
            let task = Process()
            task.launchPath = Bundle.main.resourcePath! + "/writeas"
            task.arguments = ["--font", Preferences.getFont().rawValue]
            let pipe = Pipe()
            task.standardInput = pipe
            task.launch()
            let fh: FileHandle = pipe.fileHandleForWriting
            fh.write(self.writerText.textStorage!.string.data(using: .utf8)!)
            fh.closeFile()
            task.waitUntilExit()

            DispatchQueue.main.async {
                var notification = NSUserNotification()

                // All these values are optional
                notification.title = "Published!"
                notification.informativeText = "The link is copied — press ⌘+V to share it."
                notification.soundName = NSUserNotificationDefaultSoundName

                NSUserNotificationCenter.default.deliver(notification)
            }
        }
    }

    func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
        return true
    }

    func toggle(isNight: Bool) {
        let darkBG = NSColor(red:0.13, green:0.13, blue:0.13, alpha:1.0)
        if isNight {
            self.view.window!.backgroundColor = darkBG
            self.writerText.backgroundColor = darkBG
            self.writerText.textColor = NSColor.white
        } else {
            self.view.window!.backgroundColor = NSColor.white
            self.writerText.backgroundColor = NSColor.white
            self.writerText.textColor = NSColor.black
        }
    }

    func adjustTextSize(increment: Bool) {
        var size = Preferences.getFontSize()
        if increment {
            size += 2
        } else {
            size -= 1
        }
        self.writerText.font = NSFont(name: "Lora", size: size)
        UserDefaults.standard.set(String(Int(size)), forKey: "editor_text_size")
        configureWindow()
    }

    func setFont(_ font: Preferences.PostFont) {
        self.writerText.font = NSFont(name: font.typeface, size: Preferences.getFontSize())
    }
}

